How to get an integer value from JSON data in the iPhone application

advertisements

I am parisng data using following date which is in JSON

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

Using Follwing Code

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];

    }

Book Class

    @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;
}


that is because CatId is of tyoe NSString

Change it to NSNumber and try

Hope this helps.