如何使用NSJSONSerialization从JSON对象获取值

时间:2013-10-14 14:58:27

标签: objective-c json nsdictionary

我可以检索JSON对象并显示它,但如何从“lat”和“lng”获取值以在Xcode中使用?

我的代码:

NSString *str=[NSString stringWithFormat:@"https://www.<WEBSITE>];
NSURL *url=[NSURL URLWithString:str];
NSData *data=[NSData dataWithContentsOfURL:url];
NSError *error=nil;

NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:data
                                                           options:kNilOptions
                                                             error:&error];
NSLog(@"Your JSON Object: %@ Or Error is: %@", dictionary, error);

JSON对象:

(
    {
    response =         {

        lat = "52.517681";
        lng = "-115.113995";

    };
}

我似乎无法访问任何数据。我试过了:

NSLog(@"Value : %@",[dictionary objectForKey:@"response"]);

我也尝试了很多变种,比如

NSLog(@"Value : %@",[[dictionary objectForKey:@"response"] objectForKey:@"lat"]);

但它总是以崩溃结束:

-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x15dd8b80

我注意到,当我进行调试时,'字典'只包含1个对象。如何将我的JSON对象转换为具有密钥对的NSDictionary?这个JSON对象是否格式错误?

3 个答案:

答案 0 :(得分:5)

那个特定的JSON对象是NSArray,而不是NSDictionary,这就是为什么它不能识别选择器,并且你没有收到警告,因为NSJSONSerialization JSONObjectWithData返回一个id。

尝试

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

答案 1 :(得分:0)

似乎返回的JSON不是NSDictionnary对象,而是NSArray。像这样更改你的代码:

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

responseArray包含一个dictionnary对象(或许多?)然后你就像这样访问主题:

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

答案 2 :(得分:-3)

这是我写的应用程序的剪辑...基本上得到一个 NSData 对象,通常来自一个响应,并使用 NSJSONSerialization JSONObjectWithData:选项:错误这将产生 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"];