Cocoa - 解析JSON字符串

时间:2012-10-03 11:05:59

标签: json cocoa nsjsonserialization

我知道网络上有很多关于此的例子,但我已经尝试了所有的东西,而且我错过了一些东西。我想将一个JSON字符串解析为一个dicionary。

E有服务器的响应:

{"type":"response", "action":"mkac", "result":"[{"Band":"Adele","Hits":422},{"Band":"Bryan Adams","Hits":93},{"Band":"Adai","Hits":30},{"Band":"Adamo","Hits":18},{"Band":"Adelle","Hits":15}]"}

我做了:

NSError *parseError = nil;
                        NSDictionary *outputDictionary = 
                        [NSJSONSerialization JSONObjectWithData: [output dataUsingEncoding:NSUTF8StringEncoding]
                                                        options: NSJSONReadingMutableContainers
                                                          error: &parseError];
                        NSLog(@"server said: %@", [outputDictionary objectForKey:@"result"]);

但是outputDictionary总是给我null。

任何人都可以帮助我吗?

非常感谢。

2 个答案:

答案 0 :(得分:2)

是的,你的json格格不入。如果你正确地格式化它,你会明白为什么:

{
  "type":"response", 
  "action":"mkac", 
  "result":"[{"Band":"Adele","Hits":422},{"Band":"Bryan Adams","Hits":93},{"Band":"Adai","Hits":30},{"Band":"Adamo","Hits":18},{"Band":"Adelle","Hits":15}]"
}

您会注意到"result"的值以"字符开头,这意味着该值在技术上为"[{"。但在此之后,它会遇到Band。由于Band未用双引号括起(或以,}开头等),因此会生成解析错误。如果您在[{之前和}]之后立即删除双引号,则它会正确解析:

{
  "type":"response", 
  "action":"mkac", 
  "result":[
    {
      "Band":"Adele",
      "Hits":422
    },
    {
      "Band":"Bryan Adams",
      "Hits":93
    },
    {
      "Band":"Adai",
      "Hits":30
    },
    {
      "Band":"Adamo",
      "Hits":18
    },
    {
      "Band":"Adelle",
      "Hits":15
    }
  ]
}

答案 1 :(得分:0)

我弄清楚发生了什么。 json字符串无效,因为“[我必须用[

替换]