将JSON提要转换为NSDictionary

lin*_*rts 29 objective-c nsdictionary nsarray ios sbjson

JSON_CATEGORY_DATA_URL_STRING我的Feed网址在哪里,返回正常:

[
    {
        "group":"For Sale",
        "code":"SSSS"
    },
    {
        "group":"For Sale",
        "category":"Wanted",
        "code":"SWNT"
    }
]
Run Code Online (Sandbox Code Playgroud)

我似乎无法从以下代码中获得一个好的NSDictionary(或NSArray):

+ (NSDictionary *)downloadJSON
{

NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:@"%@", JSON_CATEGORY_DATA_URL_STRING];
NSLog(@"%@",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];    
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
NSDictionary *json_dict = (NSDictionary *)json_string;
NSLog(@"json_dict\n%@",json_dict);
    NSLog(@"json_string\n%@",json_string);

return json_string;
}
Run Code Online (Sandbox Code Playgroud)

我已经阅读了很多这方面的帖子,但我没有得到它.

lag*_*gos 100

使用IOS5,您可以使用NSJSONSerialization来序列化JSON.

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
Run Code Online (Sandbox Code Playgroud)

希望这对你有所帮助.

  • NSJSONWritingPrettyPrinted是一个在writeJSONObject:中使用的写入选项,如果在此上下文中使用它,您将获得应用于读取的NSJSONReadingMutableContainers的效果. (2认同)

Car*_*zey 8

您不能只是将字符串转换为字典并期望它解析JSON.您必须使用JSON解析库来获取该字符串并将其转换为字典.

  • 有关Objective-C的JSON库列表,请查看http://cocoaobjects.com/?s=json (2认同)