使用 SBJSON 解析 JSON,问题

Posted

技术标签:

【中文标题】使用 SBJSON 解析 JSON,问题【英文标题】:Parsing JSON using SBJSON, issue 【发布时间】:2014-06-23 12:33:37 【问题描述】:

我收到了一个预测形式的 JSON 响应。 使树看起来像这样:

 "data":
           "img":"image":"http:\/\/testingpage.com\/images\/frog_320x480_23.jpg",      
           "link":"http:\/\/google.com","verbose":"Hi there", 
           "figures":[ 
                        "ID":"16","TYPE":"sailor","COLOR":"1E90FFFA","ICON":"sailor",
                       "ID":"32","TYPE":"pilot","COLOR":"32CD32BC","ICON":"pilot"
                     ]
          

我正在使用 SBJSON 库。 我得到了我的价值观

NSString *jsonString = [[NSString alloc] initWithData:iData 编码:NSUTF8StringEncoding]; NSDictionary *results = [jsonString JSON值];

并获得我需要的钥匙:

结果 objectForKey:@"keyname"]

到目前为止一切顺利。

现在发生的事情是,我收到了来自不同提供商的回复,结果在性质上完全不同:

[
      "TEMPValues": 
                   "temp1": 13.2,
                   "temp2":11.1, 
                   "temp3":11.2,
                   "temp4":13.4
                 , 
       "semipath":"pollution", 
       "value":"AXT" 
      ,
       "TEMPValues": 
                   "temp1":19.3,
                   "temp2":12.1, 
                   "temp3":10.8,
                   "temp4":13.1, 
        "semipath":"pollution",
        "value":"AUT"
      
]

我这里有两个问题:

    我不知道如何访问这些值,因为它们位于根数组中。并且该数组没有我可以参考的键。那么这种结构应该采用什么方法呢?如果我需要获取数组中TEMPValues的第一个对象的temp1

    每当我尝试使用results objectForKey:@"keyname"] 获取值时,我都会得到一个SIGABRT,因为results 被识别为一个数组

【问题讨论】:

【参考方案1】:

你必须像这样做类似的。

  -(void) retrieveData
       NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"yoururl"]];

      [request setHTTPMethod:@"GET"];

      [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"TEMPValues"];

      NSError *err;

      NSURLResponse *response;

      NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

      NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];


     variable=[[jsonArray objectAtIndex:0]objectForKey:@"keyname"];
   

【讨论】:

【参考方案2】:

首先创建值数组

NSArray *results = (NSArray *)[jsonString JSONValue];

之后迭代这个数组

for(int i= 0; i < results.count; i++) 
    NSDictionary *dic = (NSDictionary *)[results objectAtIndex:i];

【讨论】:

以上是关于使用 SBJSON 解析 JSON,问题的主要内容,如果未能解决你的问题,请参考以下文章

iOS JSON 解析为 NSDictionary,然后使用 SBJson 解析为 NSArray

如何使用 SBJson 和 Objective-C 解析和提取嵌套的 JSON 响应

不要使用SBJSON(json-framework)

不要使用SBJSON(json-framework)

SBJson 解析后的执行 (__NSArrayM objectForKey:)

SBJSON 解析器内存泄漏