Code cracker
Code cracker

Reputation: 3166

Parse from JSON response

I am getting the JSON response

(
        {
        Response = success;
        UserId = 287;
    }
)

I tried to parse the user id with below code

NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&e];
    NSLog(@"%@", dataDictionary);
    NSString *useridstring=[dataDictionary valueForKey:@"UserId"];

But am getting the user id ( 287 ). Please suggest me that how to get user id without paraparentheses

Upvotes: 0

Views: 71

Answers (2)

rishi
rishi

Reputation: 11839

You need to fetch integer value from your JSON response.

int userid = [[dataDictionary valueForKey:@"UserId"] intValue];

If getting parentheses in integer response too, then it is problem with JSON response recived. for a workaround you can use -

NSString *useridstring=[dataDictionary valueForKey:@"UserId"];
int userid = [[useridstring substringWithRange:NSMakeRange(1, useridstring.length - 2)] intValue]

EDIT --

You are getting an array in response, for this you have to use -

int userid = [[dataDictionary valueForKey:@"UserId"] firstObject];

Upvotes: 1

Milo
Milo

Reputation: 5091

Your response is not a dictionary, it's an array. So your code should look like this:

NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&e];
NSLog(@"%@", dataArray);
NSDictionary *dataDictionary = dataArray[0]; //Same as objectAtIndex:
NSString *userIDString = dataDictionary[@"UserID"]; //Same as objectForKey:
//If you're still getting parens try this:
//int userIDInt = [dataDictionary[@"UserID"] intValue];

Upvotes: 1

Related Questions