2011-08-06 94 views
1

我有一个JSON字符串:SBJson诠释解析

{"1":{"homeTeam":"Home01","awayTeam":"Away01","homeScore":0,"awayScore":0,"gameID":1},"2":{"homeTeam":"Home11","awayTeam":"Away11","homeScore":0,"awayScore":0,"gameID":2},"3":{"homeTeam":"Home21","awayTeam":"Away21","homeScore":0,"awayScore":0,"gameID":3}} 

,我想变成一个Objective-C类:

#import <Foundation/Foundation.h> 


@interface ScoreKeeperGame : NSObject { 

} 

@property (nonatomic, retain) NSString *homeTeam; 
@property (nonatomic, retain) NSString *awayTeam; 
@property (nonatomic, assign) int homeScore; 
@property (nonatomic, assign) int awayScore; 
@property (nonatomic, assign) int gameID; 

- (id) init: (NSString *) homeTeam 
    awayTeam: (NSString *) awayTeam; 

- (id) init: (NSDictionary *) game; 

@end 

我通过NSDictionary的 “游戏” 通过JSON在( JSON字符串代表一个HashMap,所以第一场比赛):

{"homeTeam":"Home01","awayTeam":"Away01","homeScore":0,"awayScore":0,"gameID":1} 

当我尝试使用这个类:

#import "ScoreKeeperGame.h" 


@implementation ScoreKeeperGame 
@synthesize homeTeam=_homeTeam, awayTeam = _awayTeam, homeScore = _homeScore, awayScore  = _awayScore, gameID = _gameID; 

- (id) init: (NSString *) homeTeam 
    awayTeam: (NSString *) awayTeam 
{ 
    self = [super init]; 
    self.homeTeam = homeTeam; 
    self.awayTeam = awayTeam; 

NSLog(@"away: %@", awayTeam); 
return self; 
} 

- (id) init: (NSDictionary *) game 
{ 
    self = [super init]; 
    if(self) 
    { 
    self.homeTeam = [game objectForKey:@"homeTeam"]; 
    self.awayTeam = [game objectForKey:@"awayTeam"]; 
    self.awayScore = (int) [game objectForKey:@"awayScore"]; 
    self.gameID = [game objectForKey:@"gameID"]; 

    NSLog(@"game awayScore: %d", self.awayScore); 
    NSLog(@"game gameID: %@", [NSNumber numberWithInt:self.gameID]); 
    } 
return self; 
} 

@end 

yourScore和gameId打印为大数字(也许指针)?

我已经试过

self.awayScore = [NSNumber numberWithInt: [game objectForKey:@"awayScore"]]; 

但是,这似乎并没有擦出火花。

如何从游戏对象中获取int的值?

po game生产:

{ 
awayScore = 0; 
awayTeam = Away01; 
gameID = 1; 
homeScore = 0; 
homeTeam = Home01; 
} 

谢谢!

回答

3

你必须先把它作为NSNumber拉出来。

NSNumber *myNum = [game objectForKey:@"awayScore"]; 

self.awayScore = [myNum intValue]; 

Doh!

1

,如果你想从你的JSON响应

self.awayScore = [NSNumber numberWithInt: [[game objectForKey:@"awayScore"] intValue]]; 

获得整数值作为你的反应会是在NSString的你可以试试这个。

0

iOs 6.0,现在只是[游戏[@“awayScore”] intValue]