2012-08-08 261 views
-2

这是json响应我该如何解析它?如何解析json响应

[ { “ID”: “35”, “名称”: “Jalsa” } ]

[ { “ID”: “32”, “名称”:” Nandhini” } ]

+0

不是这个是无效的 – 2012-08-08 09:03:40

+0

我贴的代码不起作用? – 2012-08-08 09:17:59

+0

这不再是有效的json响应。这是2种不同的反应? – 2012-08-08 09:21:53

回答

3

有苹果一类被称为

NSJSONSerializa重刑

您可以用下面的方法来分析你的JSON数据

+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error 

欲了解更多信息请参考苹果的文档:http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

编辑:

我不知道如何你是否提出这样的要求? NSURLConnection的

假设你已经在你的

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 

方法

充满了你的_recievedData,如果你需要了解如何接收数据的更多的帮助,你可以得到你的阵列这样

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSArray *recivedArray = [NSJSONSerialization JSONObjectWithData:_receivedData options:0 error:nil]; 
} 

你可以在这里找到例子https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html

+0

谢谢你,但是json的响应是数组里面的字典再次数组在字典中。请帮我 – gangadhar 2012-08-08 09:11:11

+0

我编辑了我的答案 – Mert 2012-08-08 10:55:22

0

如果您需要支持iOS 4.x,则可以使用JSONKit,因为NSJSONSerialization仅在iOS 5.x之后可用。

JSONKit也有很棒的性能。在GitHub的项目页面上检查比较结果。

1

我们使用的NSArray当表达式之间“[”,“]”
我们使用的NSDictionary当表达式是内部“{”,“}”

在我们的情况下,JSON是数组包含2个字典。每个字典包含2个键值对。

NSError *e = nil; 
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: 
NSJSONReadingMutableContainers error: &e]; 
if (e!=nil) { 
    // Handle error 
    return; 
} 
for (NSDictionary *dict in jsonArray) 
{   
    NSString *theID = [dict objectForKey:@"id"]; 
    NSLog(@"ID:%@" , theID); 

    NSString *name = [dict objectForKey:@"name"]; 
    NSLog(@"Name: %@" , name); 
} 
+0

谢谢你,但是json的响应是数组里面的字典再次数组里面的字典。请帮助我George – gangadhar 2012-08-08 09:09:00

+0

好的,你能告诉我原始的json是怎么样的吗? – 2012-08-08 09:10:15