Search code examples
iosobjective-cjsonsbjson

JSON Objective-C Parsing Fail


I have written the following code but I keep on getting nil. I have tried many different variations of this but I am failing exceptionally hard.

This is what I am getting from the server. Two objects.

[{"description":"yolo.","name":"ye","id":1},{"description":"sMITH","name":"John","id":2}]

Any help would be greatly appreciated...... Thanks.

    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
    SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
    NSArray *jsonObjects = [jsonParser objectWithData:response];
    NSMutableString *yolo = [[NSMutableString alloc] init];

            for ( int i = 0; i < [jsonObjects count]; i++ ) {
                NSDictionary *jsonDict = [jsonObjects objectAtIndex:i];
                NSString *IDID = [jsonDict objectForKey:@"id"];
                NSString *name = [jsonDict objectForKey:@"name"];

                NSLog(@"ID: %@", IDID); // THIS DISPLAYS

                [yolo appendString: IDID];    // THIS seems to be causing the new error...
                [yolo appendString:@": "];
                [yolo appendString: name];
                NSLog(@"%@", yolo);           // RETURNS NIL    
    }

EDIT:

currently my new error is...

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSDecimalNumber length]: unrecognized selector sent to instance 0x81b89f0'


Solution

  • Looks like your [jsonDict objectForKey:@"id"] is an NSNumber(or NSDecimalNumber) and not an NSString. You should change the line NSString *IDID = [jsonDict objectForKey:@"id"]; to,

    id myObject = [jsonDict objectForKey:@"id"];
    NSString *IDID = nil;
    
    if ([myObject isKindOfClass:[NSNumber class]]) {
       IDID = [[jsonDict objectForKey:@"id"] stringValue];
    } else {
       IDID = [jsonDict objectForKey:@"id"];
    }
    

    This error appeared now since earlier you were not initializing NSMutableString *yolo and you were using appendString: on a nil object. Since now it is initialized as NSMutableString *yolo = [[NSMutableString alloc] init]; it is trying to call appendString on NSMutableString object which accepts only NSString type as its inputs where as you are passing an NSNumber in it. length is a method which appendString: internally calls. So you need to change this as well.