解析JSON - iPhone

时间:2012-07-17 11:53:16

标签: iphone ios json

我是json的新手,我需要你的帮助。

我收到了这样的JSON字符串:

{"network":
   {
   "network_id":111,
   "name":"test name",
   "city":"test city",
   "country":"test country",
   "description":"test desc"
   }
}

如何处理此字符串并拆分键/值以便在我的视图中使用它们?

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {    
    [connection release];

    NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];

    self.responseData = nil;

//*********** How I can parse responseString *********//

[networkIDLabel setText:@"ADD THE VALUE"];
[nameLabel setText:@"ADD THE VALUE"];


    [responseString release];

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

谢谢

2 个答案:

答案 0 :(得分:5)

在iOS 5及更高版本中,您可以使用NSJSONSerialization直接解析响应数据:

[NSJSONSerialization JSONObjectWithData:self.responseData …];

如果您想支持早期版本的iOS,可以使用JSONKit

答案 1 :(得分:2)

在objective-c中,json可以表示为Dictionary

-(void)getData:(NSData*)response{

 // You have to include the SBJSON or else you can also use the NSJSONSerialization

 //NSDictionary *jsonData          =           [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&erro];

SBJSON *parse                               =           [[SBJSON alloc]init];

NSString *jsonString                        =           [[NSString alloc] initWithData:response
                                                                              encoding:NSUTF8StringEncoding]; 

NSDictionary *jsonData                      =           [parse objectWithString:jsonString error:&erro];
NSDictionary *insideData                          =           [jsonData objectForKey:@"network"];

if(![insideData isKindOfClass:[NSNull class]])
{

        NSString *data1         =       [insideData objectForKey:@"network_Id"];

         NSString *data2         =       [insideData objectForKey:@"name"];


 }

}