NSJSONSerialization不解析此JSON

时间:2013-10-18 06:23:57

标签: ios objective-c json nsdictionary nsjsonserialization

我正在尝试解析这个看起来很好的JSON,但是NSJSONSerialization并不认为相同的AFAIK,因为它返回NSArray

这是我的代码:

NSData* gamesData = [NSData dataWithContentsOfURL:
                        [NSURL URLWithString:@"http://s42sport.com/polarice/json/games.json"]
                        ];

    NSDictionary* json = nil;
    if (gamesData) {
        json = [NSJSONSerialization
                JSONObjectWithData:gamesData
                options:kNilOptions
                error:nil];
        NSLog(@"%d",json.count);
    }

问题是,

JSON有什么问题?为什么NSSerialization没有给我返回NSDictionary?

编辑:是的,我刚刚了解了[...] vs {...}。谢谢。

3 个答案:

答案 0 :(得分:2)

通过这种方式解析你的json

NSURL * url=[NSURL URLWithString:@"http://s42sport.com/polarice/json/games.json"];

NSData * data=[NSData dataWithContentsOfURL:url];

NSError * error;

NSMutableDictionary * json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];

NSLog(@"%@",json);

NSArray * array1=[json valueForKey:@"c"];

NSLog(@"%@",array1);

试试这段代码。这肯定会对你有用。

答案 1 :(得分:1)

NSDictionnary应该用于Object,而NSArray用于JSON数组

NSArray* json = nil;
if (gamesData) {
    json = [NSJSONSerialization
            JSONObjectWithData:gamesData
            options:kNilOptions
            error:nil];
    NSLog(@"%d",json.count);
}

答案 2 :(得分:0)

您列出的JSON文件是一个数组(它以方括号开头和结尾),因此Objective-C反映了NSArray根对象。