如何使用NSJSONSerialization从JSON对象获取

如何使用NSJSONSerialization从JSON对象获取

本文介绍了如何使用NSJSONSerialization从JSON对象获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can retrieve the JSON object and display it, but how do I get the value from "lat" and "lng" to use in 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";

    };
}

)

我似乎无法访问任何数据.我尝试过:

I cant seem to access any of the data. I've tried:

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

我还尝试了很多类似的方法

I've also tried a bunch of variations like

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

但是它总是以崩溃告终:

But it always ends up with a crash:

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

在调试过程中,我注意到字典"仅包含1个对象.如何将我的JSON对象转换为具有密钥对的NSDictionary?这个JSON对象格式不正确吗?

I've noticed when I am going through debugging that 'dictionary' only consists 1 object. How do I convert my JSON object into a NSDictionary with key pairings? Is this JSON object in the wrong format or something?

推荐答案

该特定的JSON对象是NSArray,而不是NSDictionary,这就是为什么它无法识别选择器的原因,并且由于NSJSONSerialization JSONObjectWithData而没有得到警告返回ID.

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.

尝试

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

这篇关于如何使用NSJSONSerialization从JSON对象获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:14