[英]JSONKit Parsing Nested JSON with Objective-C
I am trying to parse my nested JSON with JSONKit and the 2nd level JSON isn't being parsed correctly. 我正在尝试使用JSONKit解析嵌套的JSON,并且第二层JSON没有正确解析。
Here's sample JSON... 这是示例JSON ...
{
"app": {
"content": "[{\\\"Id\\\":\\\"1\\\",\\\"Name\\\":\\\"John\\\"},{\\\"Id\\\":\\\"2\\\",\\\"Name\\\":\\\"John\\\"}]"
}
}
and Here's my code... 这是我的代码...
NSString *jsonString = "...long nested json string...";
NSDictionary *jsonParsed = [jsonString objectFromJSONString];
NSString *content = [[jsonParsed objectForKey:@"app"] objectForKey:@"content"];
NSDictionary *jsonContent = [content objectFromJSONString];
NSLog(@"%@", jsonContent);
Where am I going wrong? 我要去哪里错了?
This is quite easy to answer: You are escaping \\
as well as "
. So your result in the NSString* content
will be \\"
. 这很容易回答:您正在转义
\\
和"
。因此,您在NSString* content
中的结果将是\\"
。 This is something your JSON parser won't digest. 这是您的JSON解析器不会消化的东西。 So use instead of
\\\\\\"
this \\"
. 因此,请使用
\\\\\\"
this \\"
代替。
If you replace the content string with following: 如果将内容字符串替换为以下内容:
"[{\"Id\":\"1\",\"Name\":\"John\"},{\"Id\":\"2\",\"Name\":\"John\"}]"
It will be parsed correctly. 它将被正确解析。
JSON.parse("[{\"Id\":\"1\",\"Name\":\"John\"},{\"Id\":\"2\",\"Name\":\"John\"}]")
>>> [Object { Id="1", Name="John"}, Object { Id="2", Name="John"}]
Maybe you have escaped the content string twice at somewhere in your code. 也许您在代码中的某个位置两次对内容字符串进行了转义。
I just used firebug to see if the JSON was correct. 我只是使用firebug来查看JSON是否正确。 JSONKit is the same:
JSONKit相同:
clowwindy:~ clowwindy$ cat /tmp/input.txt
{
"app": {
"content": "[{\"Id\":\"1\",\"Name\":\"John\"},{\"Id\":\"2\",\"Name\":\"John\"}]"
}
}
NSError *error;
NSString *input = [NSString stringWithContentsOfFile:@"/tmp/input.txt" encoding:NSUTF8StringEncoding error:&error];
NSString *jsonString = input;
NSDictionary *jsonParsed = [jsonString objectFromJSONString];
NSString *content = [[jsonParsed objectForKey:@"app"] objectForKey:@"content"];
NSDictionary *jsonContent = [content objectFromJSONString];
NSLog(@"%@", jsonContent);
NSLog(@"%@", content);
2012-01-02 00:26:39.818 testjson[12700:707] (
{
Id = 1;
Name = John;
},
{
Id = 2;
Name = John;
}
)
2012-01-02 00:26:39.822 testjson[12700:707] [{"Id":"1","Name":"John"},{"Id":"2","Name":"John"}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.