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

Hbo*_*bre 4 json objective-c 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);
Run Code Online (Sandbox Code Playgroud)

JSON对象:

(
    {
    response =         {

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

    };
}
Run Code Online (Sandbox Code Playgroud)

)

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

NSLog(@"Value : %@",[dictionary objectForKey:@"response"]);
Run Code Online (Sandbox Code Playgroud)

我也尝试了很多变化

NSLog(@"Value : %@",[[dictionary objectForKey:@"response"] objectForKey:@"lat"]);
Run Code Online (Sandbox Code Playgroud)

但它总是以崩溃告终:

-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x15dd8b80
Run Code Online (Sandbox Code Playgroud)

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

JuJ*_*oDi 5

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

尝试

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