【问题标题】:SBJson int parsingSBJson int 解析
【发布时间】:2011-10-21 08:15:54
【问题描述】:

我有一个 json 字符串:

{"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

awayScore 和 gameId 打印为大数字(可能是指针)?

我试过了

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

但这似乎也不起作用。

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

po game 产生:

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

谢谢!

【问题讨论】:

    标签: iphone objective-c json int


    【解决方案1】:

    iOs 6.0,现在只是 [game[@"awayScore"] intValue]

    【讨论】:

      【解决方案2】:

      你必须先把它作为一个 NSNumber 取出来。

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

      哇!

      【讨论】:

        【解决方案3】:

        如果你想从你的 JSON 响应中获取整数值,你可以试试这个

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

        因为您的响应将在 nsstring 中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-08-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多