【问题标题】:iOS: JSON parsing to NSArray?iOS:JSON 解析为 NSArray?
【发布时间】:2014-08-28 12:35:08
【问题描述】:

您好,我收到以下 JSON 作为响应,但在尝试将其解析为 NSArray 时出现错误。

NSArray * resp = [JSON objectForKey@"CONVCOLL"];

它对上面的行抛出异常。请帮忙

(
 {
        ACT1 = "<null>";
        ACT2 = "<null>";
        AUTRECERTI = "<null>";
        AUTRESTI = "<null>";
        CONVCOLL = "CCT romande du second oeuvre";
        DESCPHILO = "<null>";
        DESCSUCC = "<null>";
        DIRECTION = "M. Aldo Zoppi, chef d'entreprise";
        DISPHYGSEC = 1;
        FILIALES = "<null>";
        ISO14000 = 0;
        ISO9000 = 0;            
        ZONEACT = "La Riviera, Lavaux et Lausanne";
    },
        {
        ACT1 = "<null>";
        ACT2 = "<null>";
        AUTRECERTI = "<null>";
        AUTRESTI = "<null>";
        CONVCOLL = "<null>";
        DESCPHILO = "<null>";
        DESCSUCC = "<null>";
        DIRECTION = "<null>";
        DISPHYGSEC = 0;
        FILIALES = "<null>";
        ISO14000 = 2;
        ISO9000 = 1;            
        ZONEACT = "<null>";
    },
        {
        ACT1 = "<null>";
        ACT2 = "Volets en aluminium";
        AUTRECERTI = "<null>";
        AUTRESTI = "<null>";
        CONVCOLL = "<null>";
        DESCPHILO = "<null>";
        DESCSUCC = "<null>";
        DIRECTION = "M. Denis Zurbuchen, directeur et M. Jacques Zurbuchen, directeur d'exploitation";
        DISPHYGSEC = 1;
        FILIALES = "<null>";
        ISO14000 = 0;
        ISO9000 = 0;            
        ZONEACT = "<null>";
    }
)

【问题讨论】:

  • 看起来你的 JSON 是 JSONArray,而不是 JSONObject,循环遍历 JSONObjects 的 JSONArray,并在每个 JSONOBject 上进行上述调用。
  • 读取(并包含)异常消息或其他错误症状。
  • -1 不包括确切的异常消息。 (但可以猜测它类似于“无法识别的选择器”——最外层的“层”是一个数组,而不是字典。)
  • 首先,问题中贴出的JSON无效。 JSON 需要以 '[' 或 '{' 开头。圆括号 '(' 不是有效的 JSON 标记。

标签: ios objective-c json nsarray


【解决方案1】:

您的 URL 响应是 NSData 的一个实例。所以你可以解析它并遍历你收到的数组:

NSArray *JSONArray = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];

for(NSDictionary *entry in JSONArray) {
    NSLog(@"CONVCOLL: %@", [entry objectForKey:@"CONVCOLL"]);
}

【讨论】:

  • 他已经解析了数据。他的转储是一个 NSArray,而不是 JSON。
  • JSON是解析后的数据,所以你有一个数组。这意味着,您必须正确访问它的值。您必须遍历条目(如在我的代码中),或者您必须按索引访问:[JSON objectAtIndex:0];。您的数组包含NSDictionaries。这意味着(就像在我的代码中一样):[[JSON objectAtIndex:0] objectForKey:@"CONVCOLL"];
【解决方案2】:

试试下面的代码...

    NSString *response=[request responseString];

    NSArray *responseArray=[response JSONValue];

    for(NSDictionary *dict in responseArray)
    {

    self.convcoll.text=[dict objectForKey:@"CONVCOLL"];

    }

如果你使用 ASIFormDataRequest 来解析..

NSArray * resp = [JSON objectForKey@"CONVCOLL"];// this way of retrieving is not correct for above JSON..

希望对你有帮助..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    相关资源
    最近更新 更多