如何在对象C中解析具有多个实例的JSON [英] How to parse JSON with multiple instance in Object C

查看:111
本文介绍了如何在对象C中解析具有多个实例的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何使用NSJSONSerialization

Possible Duplicate:
How to use NSJSONSerialization

我正在测试在iphone应用程序上使用我的网站的Web服务. 有问题的JSON是:

I am testing to use the web service of my website on iphone Application. The JSON with problem is that:

[
    {
        "name": "Jason1",
        "age": 20
    },
    {
        "name": "Jason2",
        "age": 40
    },
    {
        "name": "Jason3",
        "age": 60
    }
]

我的代码:

   NSData *jasonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://localhost:3000/all_personal_information.json"]];
    NSDictionary *json = nil;
    if (jasonData) {
        json = [NSJSONSerialization JSONObjectWithData:jasonData options:kNilOptions error:nil];
    }

代码与{"name":"jason","age":20}一起正常工作 我可以使用json[@"name"]json[@"age"]

The code work fine with {"name":"jason","age":20} and I can get the values by using json[@"name"] and json[@"age"]

但是我不知道如何从有问题的JSON获取值. 我试图使用[json enumerateKeysAndObjectsWithOptions]横穿字典. 但是我会得到一个错误:

But i don't know how to get the value from the JSON with problem. I tried to use [json enumerateKeysAndObjectsWithOptions] to transverse the dictionary. But I will get an error:

enumerateKeysAndObjectsWithOptions:usingBlock:]: unrecognized selector sent to instance 0x89b2490

但是当我将[json description]登录到控制台时,我可以获得完整的JSON.

But I can get the full JSON when I Log the [json description] into console.

推荐答案

将其放入数组中.例如

NSData *jasonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://localhost:3000/all_personal_information.json"]];
NSDictionary *json = nil;
if (jasonData) {
    NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jasonData options:NSJSONReadingMutableContainers error: &e];
}

该数组将包含您的

{
 "name": "Jason1",
 "age": 20
}

etc在其各个索引中.当您想获取其中的值时,可以使用以下方法获取值

etc in its individual indexes. when u want to get the values in it, you can use this below method to get the values

NSDictionary *userName = [jsonArray objectAtIndex:1];
NSString *stringName = [userName valueForKey:@"name"];

这篇关于如何在对象C中解析具有多个实例的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆