GPR
GPR

Reputation: 91

Fetch the data from JSON response

I am getting JSON response like this

[{"UserId":250,"Response":"success"}]  

I used below code to fetch the UserId

  NSDictionary *jsonDict1 = [NSJSONSerialization JSONObjectWithData:receivedData options: NSJSONReadingMutableContainers error: &e];

userId = [jsonDict1 valueForKey:@"UserId"];

but i am getting user id in the form of ( 250 ) i need to get the data without parentheses

Upvotes: 1

Views: 105

Answers (1)

Paul.s
Paul.s

Reputation: 38728

The root object in your JSON is an array you can tell this as there are square brackets around the object (which uses curly braces).

When you call valueForKey: on an array it will return a new array that contains the results of calling valueForKey: on each of the elements.

If you just want to get this first item you need to do this

NSArray *results = [NSJSONSerialization JSONObjectWithData:receivedData 
                                                   options:NSJSONReadingMutableContainers 
                                                     error:&error];

userId = results.firstObject[@"UserId"];

               Array
+-------------------------------------+
|                                     |
v                                     v
[ {"UserId":250,"Response":"success"} ]  
  ^                                 ^
  |                                 |
  +---------------------------------+
         1st object in array

Upvotes: 1

Related Questions