2012-03-05 99 views
1

可能重复:
Parse JSON in Objective-C with SBJSON使用SBJson,如何从对象数组中检索字符串列表?

我有以下JSON响应(字符串)。我想把它解析成带有所有患者姓名的NSArray

[{"pat_reg_no":"111181031P1","app_start_time":"10.15","pat_firstname":"Will Smith"}, 
{"pat_reg_no":"111181031P2","app_start_time":"11.15","pat_firstname":"Shane Watson"}, 
{"pat_reg_no":"111181031P3","app_start_time":"12.15","pat_firstname":"Michael Hussey"}, 
{"pat_reg_no":"111181031P1","app_start_time":"10.15","pat_firstname":"Will Smith"}] 

我该如何解析?

+0

请访问[这个问题](http://stackoverflow.com/questions/6509214/parse-json-in-objective-c-with-sbjson)。在这里他们谈论同样的问题,并有解决方案。 – carbonr 2012-03-05 06:24:58

回答

2

尝试以下代码。

NSString* jsonString; 
//jsonString suppose this String has That JSON Response. 

SBJSON *parser = [[[SBJSON alloc] init] autorelease]; 
NSDictionary *jsonResponse = (NSDictionary*)[parser objectWithString:jsonString error:nil]; 
NSArray *pat_reg_noArray = [jsonResponse valueForKey:@"pat_reg_no"] ; 
NSArray *app_start_timeArray= [jsonResponse valueForKey:@"app_start_time"] ; 
NSArray*firstnameArray=[jsonResponse valueForKey:@"pat_firstname"]; 

我希望它能起作用。

+0

thanx它完美的作品 – divakar 2012-03-05 07:18:20

+0

@divakar你欢迎,所以你应该投票我的答案.. !!!!!。 – Kamarshad 2012-03-05 07:29:23

+0

这是使用SBJson的_old_版本。 SBJSON类在几年前就已弃用。请使用更新的版本:-) [免责声明:我是SBJson的作者] – 2012-03-05 21:42:42

1

您已经张贴属于someKey,所以做以下

SBJSON *jsonParser = [[SBJSON alloc] init]; 
NSDictionary * dictionary = [jsonParser objectWithString:YourString]; 
NSArray * array = [dictionary objectForKey:someKey]; 
NSMutableArray *nameArray = [NSMutableArray new]; 
for (NSDictionary *dict in array) 
{ 
    [nameArray addObject:[dict objectForKey:@"pat_firstname"]; 
} 
NSLog(@"x is %@",nameArray); 
[jsonParser release]; 

希望这将解决你的问题的阵列...

0

试试这个:

NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
NSArray* array = [(NSDictionary*)[jsonString JSONValue] objectForKey:@"results"]; 
+1

必须导入“JSON.h”和“SBJson.h” – Hector 2012-03-05 06:42:34

+0

为什么'JSON。 h' *和*'SBJson.h'?这听起来不对。根据您使用的库的版本,您只需包含其中一个。 [免责声明:我是SBJson的作者。] – 2012-03-05 21:45:15

3

我写的一个演示给你。

SBJsonParser *parser = [[SBJsonParser alloc] init]; 
id jsonObj = [parser objectWithString:@"[{\"pat_reg_no\":\"111181031P1\",\"app_start_time\":\"10.15\",\"pat_firstname\":\"Will Smith\"},{\"pat_reg_no\":\"111181031P2\",\"app_start_time\":\"11.15\",\"pat_firstname\":\"Shane Watson\"},{\"pat_reg_no\":\"111181031P3\",\"app_start_time\":\"12.15\",\"pat_firstname\":\"Michael Hussey\"},{\"pat_reg_no\":\"111181031P1\",\"app_start_time\":\"10.15\",\"pat_firstname\":\"Will Smith\"}]"]; 

if ([jsonObj isKindOfClass:[NSArray class]]) { 
    for (id obj in jsonObj) { 
     if ([obj isKindOfClass:[NSDictionary class]]) { 
      NSString *name = [obj objectForKey:@"pat_firstname"]; 
      NSLog(@"name %@", name); 
     } 
    } 
} 
[parser release]; 
+0

+1对不错的一个... !!! – Kamarshad 2012-03-05 06:54:41

相关问题