Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Cocoa API解析JSON?_Json_Cocoa - Fatal编程技术网

如何使用Cocoa API解析JSON?

如何使用Cocoa API解析JSON?,json,cocoa,Json,Cocoa,我只是在学习用Xcode编码,所以这个问题很简单) 我有一个代码示例: NSData *jsonSource = [NSData dataWithContentsOfURL: [NSURL URLWithString:@"http://gooruism.com/feed/json"]]; id jsonObjects = [NSJSONSerialization JSONObjectWithData: jsonSo

我只是在学习用Xcode编码,所以这个问题很简单)

我有一个代码示例:

NSData *jsonSource = [NSData dataWithContentsOfURL:
                      [NSURL URLWithString:@"http://gooruism.com/feed/json"]];

id jsonObjects = [NSJSONSerialization JSONObjectWithData:
                  jsonSource options:NSJSONReadingMutableContainers error:nil];

for (NSDictionary *dataDict in jsonObjects) {
    NSString *title_data = [dataDict objectForKey:@"title"];
现在我想从我自己的JSON解析如下所示的值:

        {
  "took" : 4,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 14,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "carinspect",
      "_type" : "inspect",
      "_id" : "ZEDrkX9AQXKsZYdFr02ilw",
      "_score" : 1.0,
      "fields" : {
        "UserID" : [ 2 ]
      }
    }, {
      "_index" : "carinspect",
      "_type" : "inspect",
      "_id" : "778xOLe6Qy-jvnQUzmhADA",
      "_score" : 1.0,
      "fields" : {
        "UserID" : [ 2 ]
      }
    }, 
我怎样才能改变

  • 数据从
    id jsonObjects
    提取到类似
    hits.hits jsonObjects
  • 获取_id值(类似于
    NSString*title_data=[dataDict objectForKey:@“_id”];
  • 获取UserID的值(如
    NSString*title_data=[dataDict objectForKey:@“fields.UserID”];

  • 抱歉,如果我试图解释的语言很糟糕

    您通常不希望使用(x in y)对NSDictionary(表示JSON“对象”)进行排序,而是希望显式命名要获取的元素--
    NSDictionary*hits=JSONObject[@“hits”]
    (我强烈怀疑您是通过盲目复制您不懂的代码(但这是在解析JSON“数组”)而获得上述代码的。请访问JSON.org并研究JSON语法——学习只需5-10分钟,如果您不懂,您将注定要失败。)@Andreypov问题是什么?你不知道如何解析这个JSON?@meda抱歉,只是在学习…@HotLicks也许我错了,但是在hits.hits下,我有一个数组要运行。。?
    NSData *jsonSource = [NSData dataWithContentsOfURL:
                          [NSURL URLWithString:@"http://XXXXXXXX.com"]];
    
    id jsonObjects = [NSJSONSerialization JSONObjectWithData:
                      jsonSource options:NSJSONReadingMutableContainers error:nil];
    
    id jsonHits = [[jsonObjects objectForKey:@"hits"] objectForKey:@"hits"];
    
    for (NSDictionary *dataDict in jsonHits) {
        NSString *title_data = [[dataDict objectForKey:@"_source"] objectForKey:@"Number"];