2011-08-25 41 views
1

我使用以下日期是在JSON parisng数据如何获得在iPhone应用程序从JSON数据的整数值

[ 
{ 
    "categoryId": 202, 
    "name": "Sport" 
}, 
{ 
    "categoryId": 320, 
    "name": "Fritid" 
}, 
{ 
    "categoryId": 350, 
    "name": "Kultur" 
}, 
{ 
    "categoryId": 4920, 
    "name": "Diverse" 
}, 
{ 
    "categoryId": 4774, 
    "name": "Samfunn" 
} ] 

使用Follwing代码

SBJsonParser *parser = [[SBJsonParser alloc] init]; 

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.krsconnect.no/community/api.html?method=categories&appid=620&mainonly=true"]]; 
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 
NSDictionary *object = [parser objectWithString:json_string error:nil]; 
//appDelegate.books = [[NSMutableArray alloc] initWithCapacity:0]; 

appDelegate.books = [[NSMutableArray alloc] init]; 

NSArray *results = [parser objectWithString:json_string error:nil]; 
for (int i=0; i<[results count]; i++) { 
    Book *aBook = [[Book alloc] initWithDictionary:[results objectAtIndex:i]]; 
    [appDelegate.books addObject:aBook]; 


    [aBook release]; 

    } 

图书类

@interface Book : NSObject { 


NSString *catId; 


NSString *name; 

    } 

    @property(nonatomic,retain)NSString*catId; 

    @property(nonatomic,retain) NSString *name; 

    @end 


    #import "Book.h" 


@implementation Book 


@synthesize catId,name; 

-(id)init{ 
    self=[super init]; 
} 

- (id)initWithDictionary:(NSDictionary*) dict { 
    self.catId = [dict valueForKey:@"categoryId"]; self.name = 
    [dict valueForKey:@"name"]; 
    return self; 
} 
+0

我的问题是,我没有得到价值catid – ali

+0

我给出的代码initWithDict – ali

+0

catid显示其不是CFSting – ali

回答

6

那是因为CatId是tyoe NSString

更改为NSNumber并尝试

希望这会有所帮助。

+0

如果我使用NSInteger它给出了这个值在catid 79765008 – ali

+0

多数民众赞成多数民党这是因为它给变量地址的指针变量 – Robin

+0

使用intValue方法你nsinteger变量 – Robin

2

当你解析categoryId的响应时,你似乎得到了NSNumber。所以尝试通过取得NSString的NSNumber对象。

+0

你能帮助我怎么做,我已经做了,但没有成功 – ali

0

您收到的字典可能会将数值存储为NSNumber对象。所以你的catId也应该是NSNumber,或者-initWithDictionary:应该使用例如类别id将类别id提取为原语类型。 -intValue和catId应该被声明为int

顺便说一下,您应该使用-objectForKey:NSDictionary s获取对象。由于-valueForKey:执行了一些额外的处理,因此性能稍微高一些,然后调用-objectForKey:

json_string泄漏,所以可以自由地appDelegate.books

相关问题