1

有很多这样的问题,我也对 json 格式有经验,但我无法解析下面的响应(在底部):

我正在使用 NSJSONSerialization 将响应解析为 NSDictionary 但它给出了如下错误:

我的代码:

     NSString *subURL= sharedDa.ip;
        NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.69.230/tsadmin.php?tssearch=%@", subURL]]];

        NSError *error=nil;
        NSDictionary* portsResult=[NSJSONSerialization JSONObjectWithData:data options:
                              NSJSONReadingMutableContainers error:&error];
  NSDictionary * tempPorts;
    NSString *k;

        for(k in [portsResult allKeys]){
            tempPorts = [portsResult objectForKey:k];
            NSLog(@"Temporary ports: %@", tempPorts);
        } 

错误代码如下:

2012-09-28 18:47:37.508 BNTPRO ST Manager[2609:fb03] -[__NSArrayM allKeys]: unrecognized selector sent to instance 0x6b83ed0
2012-09-28 18:47:37.511 BNTPRO ST Manager[2609:fb03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM allKeys]: unrecognized selector sent to instance 0x6b83ed0'
*** First throw call stack:
(0x1568022 0x1b20cd6 0x1569cbd 0x14ceed0 0x14cecb2 0x57cd 0x28fa1e 0x28fd11 0x2a18fd 0x2a1aef 0x2a1dbb 0x2a285f 0x2a2e06 0x2a2a24 0x3e59 0x2595c5 0x2597fa 0xaee85d 0x153c936 0x153c3d7 0x149f790 0x149ed84 0x149ec9b 0x245a7d8 0x245a88a 0x1c8626 0x26d2 0x2645 0x1)
terminate called throwing an exception(lldb)

现在我的数据片段是:[{"k1":{"v":"0"}},{"k2":{"v":"0"}},{"k3":{"v":"0"}},{"k4":{"v":"0"}},{"k5":{"v":"0"}},{"k6":{"v":"0"}},{"k7":{"v":"1"}},{"k8":{"v":"0"}},{"k9":{"v":"1"}},{"k10":{"v":"0"}},{"k11":{"v":"1"}},{"k12":{"v":"0"}},{"k13":{"v":"1"}},{"k14":{"v":"0"}},{"k15":{"v":"0"}},{"k16":{"v":"0"}}] 但它仍然给出相同的错误..即使我将 iVar 描述为 NSDictionary 为什么它抱怨 nsmutable 数组?

4

1 回答 1

3

您正在解析的 JSON 是一个数组,而不是一个对象。所以结果[NSJSONSerialization JSONObjectWithData...]不是一个NSDictionary *,而是一个NSArray *

例如,对于 JSON 数据

[{"k1":{"v":"0"}}, {"k2":{"v":"0"}}]

您可以使用类似于此代码的内容(现在没有 xcode 来尝试运行它):

NSArray * arr = [NSJSONSerialization JSONObjectWithData:data options:...];
int i;
for (i = 0; i < [arr count]; i++) {
    NSDictionary * dic = [arr objectAtIndex:i];
    NSString * k;
    for (k in [dic allKeys]) {
        NSLog(@"Temporary ports: %@", [dic objectForKey:k]);
    }
}
于 2012-09-28T17:38:30.697 回答