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

Mom*_*ntH 2 parsing json ios sbjson

它应该是如此简单,但我不能让它工作.

Json响应是([{"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
Run Code Online (Sandbox Code Playgroud)

转换shoud有两个NSObjects ..每个都应该有

id:1 x:1 y:2

id:2 x:2 y:4

jon*_*oll 6

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

NSArray *jsonObject = [parser objectWithString:response error:nil];
Run Code Online (Sandbox Code Playgroud)

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

NSDictionary *firstItem = [jsonObject objectAtIndex:0];
NSString *theID = [firstItem objectForKey:@"id"];
Run Code Online (Sandbox Code Playgroud)