How to get a value from a JSON Object using NSJSONSerialization

╄→尐↘猪︶ㄣ 提交于 2019-12-04 09:52:24

That specific JSON object is an NSArray, not an NSDictionary, which is why it does not recognize the selector, and you're not getting a warning because NSJSONSerialization JSONObjectWithData returns an id.

Try

NSArray *array = [NSJSONSerialization JSONObjectWithData:data
                                                 options:kNilOptions
                                                   error:&error];
NSDictionary *dictionary = array[0];

It seems that the JSON returned is not an NSDictionnary object, but an NSArray. Change your code like this :

NSarray *responseArray = [NSJSONSerialization JSONObjectWithData:data
                                                           options:kNilOptions
                                                             error:&error];

The responseArray contains a dictionnary object ( or many ?) then you acn acces theme like this :

For ( NSDictionary *dic in responseArray){
    NSDictionnary *response = [dic objectForKey@"response"];
....
}

Here is a snip from an app I wrote...basically get an NSData object, typically from a response, and use NSJSONSerialization JSONObjectWithData:Options:Error which will produce an NSDictionary

NSError *error = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

//Make sure response came in
if(response != nil){
    NSError *error = nil;
    id data = [NSJSONSerialization JSONObjectWithData:response options:0 error:&error];

    if([data isKindOfClass:[NSDictionary class]]){
        //Create dictionary from all the wonderful things google provides
        NSDictionary *results = data;

        //Search JSON here
        NSArray *cityAndState = [[[[results objectForKey:@"results"] objectAtIndex:0] objectForKey:@"address_components"] valueForKey:@"short_name"];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!