ali
ali

Reputation: 85

How to get a integer value from JSON data in iphone application

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

Upvotes: 1

Views: 5677

Answers (3)

Neelesh
Neelesh

Reputation: 3693

that is because CatId is of tyoe NSString

Change it to NSNumber and try

Hope this helps.

Upvotes: 6

JeremyP
JeremyP

Reputation: 86651

The dictionary you are getting stores numeric values as NSNumber objects probably. So your catId should either be a NSNumber too , or -initWithDictionary: should extract the category id into a primitive type using e.g. -intValue and catId should then be declared as int.

By the way, you should use -objectForKey: to get objects from NSDictionarys. It's marginally more performant since -valueForKey: does some extra processing, then calls -objectForKey:.

Also json_string leaks and so robably does appDelegate.books.

Upvotes: 0

Pragnesh Dixit
Pragnesh Dixit

Reputation: 449

It seems that you are getting NSNumber when you parse the response for categoryId. So try by taking NSNumber object inplace of NSString.

Upvotes: 2

Related Questions