使用SBJson,如何从对象数组中检索字符串列表?

时间:2012-03-05 06:20:49

标签: iphone objective-c

  

可能重复:
  Parse JSON in Objective-C with SBJSON

我有JSON Response(String)。我想将其解析为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"}]

我如何解析这个?

4 个答案:

答案 0 :(得分: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];

答案 1 :(得分: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"];

我希望它会起作用。

答案 2 :(得分: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];

希望这能解决你的问题...

答案 3 :(得分:0)

试试这个:

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