1

我知道网络上有很多关于这个的例子,但我已经尝试了一切,但我错过了一些东西。我想将 JSON 字符串解析成字典。

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 总是给我空值。

任何人都可以帮助我吗?

非常感谢。

4

2 回答 2

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}]"
}

您会注意到 for 的值以字符"result"开头",这意味着该值在技术上是"[{". 然而在那之后,它遇到了Band。由于Band没有用双引号括起来(或前面有 a,或 a}等),因此会产生解析错误。如果您在 之前[{和之后立即删除双引号}],则它会正确解析:

{
  "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
    }
  ]
}
于 2012-10-03T14:30:00.587 回答
0

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

于 2012-10-03T14:53:07.837 回答