繁体   English   中英

Objective C解析JSON,Dictionary返回NSCFString而不是NSArray

[英]Objective C Parsing JSON, Dictionary returns a NSCFString instead of NSArray

我正在尝试做的是获取JSON feed,然后遍历结果。 但是,当我从字典中获取对象时,我一直在获取字符串而不是数组。 关于我做错了什么的任何想法?

这是JSON:

[
  {
    "_id": "4f6d9a7c1d0b4900010007ee",
    "geo_triggers": [
      {
        "_id": "4fc3e5fdc7234e0001000002",
        "location": [1,1],
        "longitude": "1",
        "latitude": "1",
        "radius": 1,
        "location_name": "Test 1"
      },
      {
        "_id": "4fc61f3762f53f0001000043",
        "location": [-71.057673,42.355395],
        "longitude": "-71.057673",
        "latitude": "42.355395",
        "radius": 1000,
        "location_name": "Test2"
      }
    ]
  }
]

这是Objective C代码:

const char* className = class_getName([result class]);
NSLog(@"Result is a: %s", className);
NSLog(@"%@", result); //string
NSArray* json = [result objectForKey:@"result"]; //should be an array of dictionaries
NSLog(@"JSON Output: %@", json);
const char* className1 = class_getName([json class]);
NSLog(@"yourObject is a: %s", className1);

这是输出:

Result is a: __NSDictionaryI
2012-10-10 17:15:15.165 App[12980:19d03] {
    result = "[{\"_id\":\"4f6d9a7c1d0b4900010007ee\",\"geo_triggers\":[{\"_id\":\"4fc3e5fdc7234e0001000002\",\"location\":[1.0,1.0],\"longitude\":\"1\",\"latitude\":\"1\",\"radius\":1,\"location_name\":\"Test 1\"},{\"_id\":\"4fc61f3762f53f0001000043\",\"location\":[-71.057673,42.355395],\"longitude\":\"-71.057673\",\"latitude\":\"42.355395\",\"radius\":1000,\"location_name\":\"Test2\"}]}]";
}
2012-10-10 17:15:15.166 App[12980:19d03] JSON Output: [{"_id":"4f6d9a7c1d0b4900010007ee","geo_triggers":[{"_id":"4fc3e5fdc7234e0001000002","location":[1.0,1.0],"longitude":"1","latitude":"1","radius":1,"location_name":"Test 1"},{"_id":"4fc61f3762f53f0001000043","location":[-71.057673,42.355395],"longitude":"-71.057673","latitude":"42.355395","radius":1000,"location_name":"Test2"}]}]
2012-10-10 17:15:15.166 App[12980:19d03] yourObject is a: __NSCFString
2012-10-10 17:15:15.166 App[12980:19d03] -[__NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0xb331800

您的result变量指向字典。 词典包含一个键。 那个键是@"result" 该键的值是字符串@"[{\\"_id\\":\\"4f6d9a7c1d0b4900010...

换句话说,您还没有真正反序列化JSON。 您需要获取关键result的值,然后通过JSON解串器运行它。

首先需要解码结果。 上面是JSON,所以我建议这样做

  1. 如果尚未安装,请下载JSONKit.h并将其包含在项目中
  2. 那你要么做

    1. NSString* json = [result JSONString]; 看输出
      要么
    2. id jsonDict = [[JSONDecoder decoder] objectWithData:responseData];一样id jsonDict = [[JSONDecoder decoder] objectWithData:responseData]; 之后,您可以执行[jsonDict objectForKey:@“ _ id”]; ///等等

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM