SBJson int parsing
I have a json string:
{"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}}
that I would like to turn into an Obj开发者_开发知识库ective-C class:
#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
I pass the json in by NSDictionary "game" (the json string represents a hashmap, so the first game is):
{"homeTeam":"Home01","awayTeam":"Away01","homeScore":0,"awayScore":0,"gameID":1}
When I try to use this class:
#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
The awayScore and gameId are printed as large numbers (maybe pointers)?
I've tried
self.awayScore = [NSNumber numberWithInt: [game objectForKey:@"awayScore"]];
But that didn't seem to work either.
How do I get the value of the int from the game object?
po game
produces:
{
awayScore = 0;
awayTeam = Away01;
gameID = 1;
homeScore = 0;
homeTeam = Home01;
}
Thanks!
You have to pull it out as an NSNumber first.
NSNumber *myNum = [game objectForKey:@"awayScore"];
self.awayScore = [myNum intValue];
Doh!
you can try this if you want to get integer value from your JSON response
self.awayScore = [NSNumber numberWithInt: [[game objectForKey:@"awayScore"] intValue]];
as your response would be in nsstring.
iOs 6.0, now it's simply [game[@"awayScore"] intValue]
精彩评论