5

我对 JSON 解析有一些问题。当我点击 URL 时,我得到如下 JSON 响应:

//JSON 1
{ "data":
  {"array":
    ["3",
       {"array":
          [
            {"id":"1","message":"Hello","sender":"inot"},
            {"id":"2","message":"World","sender":"inot"},
            {"id":"3","message":"Hi","sender":"marza"}
          ]
        }
     ]
   },
 "message":"MSG0001:Success",
 "status":"OK"
}

但是如果 data 的结果只是 1,那么 JSON 响应是这样的:

//JSON 2
{ "data":
  {"array":
    ["3",
       {"array":
          {"id":"3","message":"Hi","sender":"marza"}
       }
     ]
   },
 "message":"MSG0001:Success",
 "status":"OK"
}

我实现此代码以获取 id、消息和发件人值,并在 JSON 1 上正常工作,但在 JSON 2 上出错。我使用 JSON-Framework。问题是如何检测 JSON 响应是对象 ({ }) 还是数组 ([ ]) ?

// Parse the string into JSON
NSDictionary *json = [myString JSONValue];

// Get all object
NSArray *items = [json valueForKeyPath:@"data.array"];
NSArray *array1 = [[items objectAtIndex:1] objectForKey:@"array"];
NSEnumerator *enumerator = [array1 objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
   NSLog(@"id      = %@",[item objectForKey:@"id"]);
   NSLog(@"message = %@",[item objectForKey:@"message"]);
   NSLog(@"sender  = %@",[item objectForKey:@"sender"]);
}
4

1 回答 1

16

您可以使用id并检查您获得的对象是 NSArray 还是 NSDictionary,如下所示:

id item = [json valueForKeyPath:@"data.array"];
if ([item isKindOfClass:[NSArray class]]) {
    // item is an array
}
else if ([item isKindOfClass:[NSDictionary class]]) {
    // item is a dictionary
}
于 2010-07-18T20:12:26.980 回答