我在使用NSJSONSerialization从PHP服务器解析JSON时遇到了问题。JSLint说我的JSON是有效的,但似乎只能进入一到两级。
这本质上是我的JSON结构:
{
"products":
[{
"product-name":
{
"product-sets":
[{
"set-3":
{
"test1":"test2",
"test3":"test4"
},
"set-4":
{
"test5":"test6",
"test7":"test8"
}
}]
},
"product-name-2":
{
"product-sets":
[{
}]
}
}]
}下面是我解析它的代码:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if (json) {
NSArray *products = [json objectForKey:@"products"]; // works
for (NSDictionary *pItem in products) { // works
NSLog(@"Product: %@", pItem); // works, prints the entire structure under "product-name"
NSArray *productSets = [pItem objectForKey:@"product-sets"]; // gets nil
for (NSDictionary *psItem in productSets) {
// never happens
}
}
}我已经在这上面转了几个小时了,但我在搜索的任何地方都没有找到任何类似的东西。有没有什么我没有意识到的限制,或者我只是看不到明显的东西?
发布于 2012-08-24 00:45:55
您遗漏了一个嵌套对象
NSArray *productSets = [[pItem objectForKey:@"product-name"] objectForKey:@"product-sets"];我用这个CLI程序进行了测试
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSString *jsonString = @"{\"products\":[{\"product-name\": {\"product-sets\": {\"set-3\":{\"test1\":\"test2\", \"test3\":\"test4\"}, \"set-4\":{\"test5\":\"test6\", \"test7\":\"test8\"} }}}, {\"product-name-2\": \"2\"}]}";
// insert code here...
NSLog(@"%@", jsonString);
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
if (json) {
NSArray *products = [json objectForKey:@"products"]; // works
for (NSDictionary *pItem in products) { // works
NSLog(@"Product: %@", pItem); // works, prints the entire structure under "product-name"
NSArray *productSets = [[pItem objectForKey:@"product-name"] objectForKey:@"product-sets"]; // gets nil
for (NSDictionary *psItem in productSets) {
NSLog(@"%@", psItem);
}
}
}
}
return 0;
}请注意,json中的一些内容非常奇怪:
对于每个展平的对象,关键点应该相同。包含对象数字的键没有多大意义。如果您需要跟踪单个对象,请包含一个具有适当值的id键。
https://stackoverflow.com/questions/12095200
复制相似问题