如何使用SBJSON iPhone处理JSON响应?

时间:2011-02-25 14:58:57

标签: iphone xcode iphone-sdk-4.1

我的网络服务收到以下回复? 任何人都知道如何使用SBJSON处理它吗?

{
"match_details" : 
    {
        "score" : 86-1
        "over" : 1.1
        "runrate" : 73.71
        "team_name" : England
        "short_name" : ENG
        "extra_run" : 50
    }

"players" : 
    {
        "key_0" : 
            {
                "is_out" : 2
                "runs" : 4
                "balls" : 2
                "four" : 1
                "six" : 0
                "batsman_name" : Ajmal Shahzad *
                "wicket_info" : not out
            }

        "key_1" : 
            {
                "is_out" : 1
                "runs" : 12
                "balls" : 6
                "four" : 2
                "six" : 0
                "batsman_name" : Andrew Strauss
                "wicket_info" : c. Kevin b.Kevin
            }

        "key_2" : 
            {
                "is_out" : 2
                "runs" : 20
                "balls" : 7
                "four" : 4
                "six" : 0
                "batsman_name" : Chris Tremlett *
                "wicket_info" : not out
            }

      }

"fow" : 
    {
        "0" : 40-1
    }

}

我做过这样的事情:

2 个答案:

答案 0 :(得分:3)

导入SBJSON/JSON.h头文件并执行类似的操作...

NSString *jsonResponseString = ...your JSON response...;

NSDictionary *jsonDictionary = [jsonResponseString JSONValue];

NSDictionary *players = [jsonDictionary objectForKey:@"players"];

NSDictionary *player = [players objectForKey:@"key_0"];

NSLog( @"%@ %@ %@ %@ %@ %@ %@", [player objectForKey:@"is_out"],
  [player objectForKey:@"runs"], [player objectForKey:@"balls"],
  [player objectForKey:@"four"], [player objectForKey:@"six"],
  [player objectForKey:@"batsman_name"], [player objectForKey:@"wicket_info"] );

......等等。

答案 1 :(得分:0)

以下是如何将响应作为数组获取。但主要问题是:您想对数据做什么? ;)

SBJsonParser *parser = [[SBJsonParser alloc] init];
NSString * response = [request responseString];
NSMutableArray *array = [parser objectWithString:response error:nil];
NSMutableArray *match = [array valueForKey:@"match_details"];
NSMutableArray *players = [array valueForKey:@"players"];

// This should display your players name
for(id player in players) {
   NSLog(@"Player name: %@", [(NSDictionary *)player valueForKey:@"batsman_name"]);
}