gpt4 book ai didi

json - Cocoa - 解析 JSON 字符串

转载 作者:行者123 更新时间:2023-12-03 17:04:47 25 4
gpt4 key购买 nike

我知道网络上充满了这方面的示例,但我已经尝试了所有方法,但我遗漏了一些东西。我想将 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总是给我null。

有人可以帮我吗?

非常感谢。

最佳答案

是的,您的 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
}
]
}

关于json - Cocoa - 解析 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12707203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com