1

I have the following json returned string:

[{"status":2,"id":"-1","content":"User has entered wrong input","time":1346765646202}]

(as you can see the result is in an array that contains a single object).

How can I extract the value of status and content without Enumeration?

For now I created a dictionary and run on it with enumeration, but I don't like the solution:

NSData *jsonData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

2 Answers 2

4

Because the whole thing is wrapped in [], it will deserialize into an NSArray (of size 1) (not an NSDictionary as your code implies). The element in that array will be an NSDictionary ({}). You can get that dictionary with objectAtIndex:0 and skip your enumeration:

NSData *jsonData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *response = [json objectAtIndex:0];
NSNumber *status = [response objectForKey:@"status"];
NSString *content = [response objectForKey:@"content"];
Sign up to request clarification or add additional context in comments.

Comments

0
NSNumber * status = json[@"status"]

or

NSNumber * status = [json objectForKey: @"status"]

etc.

1 Comment

NSNumber *status = [json objectForKey: @"status"]; throws an exception: 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: please note that it's an array of json strings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.