iphone - Objective C 解析 JSON,字典返回 NSCFString 而不是 NSArray

标签 iphone objective-c xcode json

我想做的是获取 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 反序列化器运行它。

关于iphone - Objective C 解析 JSON,字典返回 NSCFString 而不是 NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12828698/

相关文章:

iphone - Objective-C 浮点舍入

ios - 在 Xcode 中查找编辑功能

xcode - 滑动长行的操作按钮位置

iphone - 如何使用 MPMusicPlayerController 关闭音量?

iphone - 如何使用 NSXMLParser 读取此 CDATA

ios - 如何将 subview 拖出父 View ?

ios - 将生成的 GIF 保存到相机胶卷?

ios - 在 Objective-C 中读取 gzip 压缩字符串失败?

iphone - 获取 NSArray 的 EXC_BAD_ACCESS

xcode - 当我从xcode 9.2中的xcode 9.3代码打开时,出现“Failed to load Project , incompatible project version”弹出窗口