iOS JSON解析为NSDictionary,然后使用SBJson解析NSArray

时间:2012-04-23 04:57:49

标签: ios json parsing sbjson

它应该是如此简单,但我不能让它发挥作用。

杰森的回应是 ([{“id”:“1”,“x”:“1”,“y”:“2”},{“id”:2,“x”:“2”,“y”:“4” }])

NSString *response = [request responseString];
//response is ([{"id":"1", "x":"1", "y":"2"},{"id":2, "x":"2", "y":"4"}])

SBJSON *parser = [[[SBJSON alloc] init] autorelease];

NSDictionary *jsonObject = [parser objectWithString:response error:NULL];
// jsonObject doesn't have any value here..Am I doing something wrong?

NSMutableArray Conversion = [jsonObject valueForKey:NULL];
//Even if I get the value of jsonObject. I don't know what to put for valueForKey here

转换shoud有两个NSObject ...并且每个都应该有

ID:1 X:1 Y:2

ID:2 X:2 Y:4

1 个答案:

答案 0 :(得分:6)

您的JSON解析器将从您的响应字符串生成NSArray,而不是NSDictionary。请注意,JSON解析器(包括SBJSON)将返回数组对象或字典对象,具体取决于要解析的json的内容。

NSArray *jsonObject = [parser objectWithString:response error:nil];

然后,您可以访问数组中的各个项目(数组元素的类型为NSDictionary),并使用valueForKey:获取每个项目的属性。

NSDictionary *firstItem = [jsonObject objectAtIndex:0];
NSString *theID = [firstItem objectForKey:@"id"];