Convert NSDictionary To JSON

丶灬走出姿态 提交于 2019-12-24 13:18:05

问题


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?


回答1:


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

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



回答2:


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]);
}


来源:https://stackoverflow.com/questions/27293760/convert-nsdictionary-to-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!