Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

ios - How can i post json string to server

This is json string that I have to post...

{
    "data": {
        "description": "",
        "current_value": "",
        "serialno": "",
        "condition": "",
        "category": "category",
        "purchase_value": "",
        "new_or_used": "",
        "gift_or_purchase": "",
        "image": ""
    },
    "subtype": "fd3102d8-bc19-424b-bca2-774a8fd7ea6f"
}

How to post as JSON?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Surely this Q us a duplicate, but here's full example code, as one long routine. Just copy and paste.

First set up the JSON...

-(void)sendTestJsonCommand
    {
    NSMutableDictionary *dict = @{
        @"heights":@"4_5_7",
        @"score":@"4",
        @"title":@"Some Title",
        @"textBody":@"Some Long Text",
        @"happy":@"y"
        }.mutableCopy;

    NSError *serr;

    NSData *jsonData = [NSJSONSerialization
        dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&serr];

    if (serr)
        {
        NSLog(@"Error generating json data for send dictionary...");
        NSLog(@"Error (%@), error: %@", dict, serr);
        return;
        }

    NSLog(@"Successfully generated JSON for send dictionary");
    NSLog(@"now sending this dictionary...
%@


", dict);

Next, correctly asynchronously send the command and json to your server...

#define appService [NSURL 
  URLWithString:@"http://www.corp.com/apps/function/user/pass/id/etc"]

    // Create request object
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:appService];

    // Set method, body & content-type
    request.HTTPMethod = @"POST";
    request.HTTPBody = jsonData;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setValue:
        [NSString stringWithFormat:@"%lu",
        (unsigned long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];

    // you would almost certainly use MBProgressHUD at this point
    // to display some sort of spinner or similar action on the UX

Finally, (A) connect correctly using NSURLConnection, and (B) correctly interpret the information which comes back to you from your server.

    [NSURLConnection sendAsynchronousRequest:request
        queue:[NSOperationQueue mainQueue]
        completionHandler:^(NSURLResponse *r, NSData *data, NSError *error)
        {

        if (!data)
            {
            NSLog(@"No data returned from server, error ocurred: %@", error);
            NSString *userErrorText = [NSString stringWithFormat:
               @"Error communicating with server: %@", error.localizedDescription]
            return;
            }

        NSLog(@"got the NSData fine. here it is...
%@
", data);
        NSLog(@"next step, deserialising");

        NSError *deserr;
        NSDictionary *responseDict = [NSJSONSerialization
                                      JSONObjectWithData:data
                                      options:kNilOptions
                                      error:&deserr];

        NSLog(@"so, here's the responseDict


%@


", responseDict);

        // LOOK at that output on your console to learn how to parse it.
        // to get individual values example blah = responseDict[@"fieldName"];
        }];

    }

Hope it saves someone some typing!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...