在iOS中理解并使用此JSON数据

oky*_*eni 2 json nsdictionary ios ios5


我创建了一个返回JSON的Web服务,我认为.返回的数据如下所示:

{"invoice":{"id":44,"number":42,"amount":1139.99,"checkoutStarted":true,"checkoutCompleted":true}}
Run Code Online (Sandbox Code Playgroud)

对我来说,这看起来像有效的JSON.

在iOS5中使用本机JSON序列化程序,我获取数据并将其捕获为NSDictionary.

NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[request responseData] options:kNilOptions error:&error];
    NSLog(@"json count: %i, key: %@, value: %@", [json count], [json allKeys], [json allValues]);
Run Code Online (Sandbox Code Playgroud)

日志的输出是:

json count: 1, key: (
    invoice
), value: (
        {
        amount = "1139.99";
        checkoutCompleted = 1;
        checkoutStarted = 1;
        id = 44;
        number = 42;
    }
)
Run Code Online (Sandbox Code Playgroud)

因此,在我看来,JSON数据具有NSString密钥"invoice",其值为NSArray ({amount = ..., check...})

所以,我将值转换为NSArray:

NSArray *latestInvoice = [json objectForKey:@"invoice"];
Run Code Online (Sandbox Code Playgroud)

但是,当单步执行时,它表示latestInvoice不是CFArray.如果我打印出数组中的值:

for (id data in latestInvoice) {
        NSLog(@"data is %@", data);
    }
Run Code Online (Sandbox Code Playgroud)

结果是:

data is id
data is checkoutStarted
data is ..
Run Code Online (Sandbox Code Playgroud)

我不明白为什么它只返回"id"而不是"id = 44".如果我将JSON数据设置为NSDictionary,我知道密钥是NSString但是值是多少?是NSArray还是其他什么?

这是我读过的教程:http: //www.raywenderlich.com/5492/working-with-json-in-ios-5

编辑:从答案来看,似乎NSDictionary*json的"价值"是另一个NSDictionary.我认为这是NSArray或NSString这是错误的.换句话说,[K,V]代表NSDictionary*json = [@"invoice",NSDictionary]

Bri*_*oll 5

问题是这样的:

NSArray *latestInvoice = [json objectForKey:@"invoice"];
Run Code Online (Sandbox Code Playgroud)

实际上,它应该是:

NSDictionary *latestInvoice = [json objectForKey:@"invoice"];
Run Code Online (Sandbox Code Playgroud)

...因为你拥有的是字典而不是数组.