SARATH SASI
SARATH SASI

Reputation: 1415

Convert NSDictionary To JSON

How to Convert NSDictionary into JSON ?

I have posted a dictionary into server using json. And in the time receiving the data from the server using GET method. the data cant be accessed using normal key calling method like

_secretanswer.text=[[NSString alloc]initWithFormat:@"%@",[customfield objectForKey:@"secanswer"]];  

the server returning a NCFString as the result.

How to convert and post a NSDictionary in the JSON format?

Upvotes: 1

Views: 1066

Answers (2)

user1078170
user1078170

Reputation:

I believe that what you're looking for is NSJSONSerialization.

This answer assumes use of NSURLConnection's block based API to execute your GET.

[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (data) {
        NSError *jsonError = nil;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
        if (dict) {
            // You got a valid NSDictionary out of your JSON response.
            NSLog(@"my returned dictionary: %@", dict);
        } else if (jsonError) {
            // JSON data could not be parsed into NSDictionary. Handle as appropriate for your application.
            return;
        }
    } else if (connectionError) {
        // Handle connection error
    }
}];

But even if you're using dataWithContentsOfURL:, the point is the same. Feed your data in to NSJSONSerialization's + jsonObjectWithData:options:error: method, check if you get a dictionary back from that, and proceed.

EDIT: If you're looking to create a JSON post body for an HTTP request from an NSDictionary, NSJSONSerialization has you covered there as well.

NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:someDictionary options:NSJSONWritingPrettyPrinted error:&error];
if (data) {
    // You got your data.
    NSLog(@"my data: %@", data);
    [someURLRequest setHTTPBody:data];
} else if (error) {
    NSLog(@"error: %@", [error localizedDescription]);
}

Upvotes: 1

vijeesh
vijeesh

Reputation: 1327

NSError * error;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&error]; 

NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]    

Upvotes: 0

Related Questions