How to get boolean value from JSON?
Let's assume this is the JSON value that I want to assign to the BOOL variable:
"retweeted": false
This is how I parse the JSON data:
NSError *error;
NSArray *timeline = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
Now I have a bool property defined as:
BOOL *retweeted;
Inside my class. When I do this while parsing JSON:
tweet.retweeted = [[[timeline objectAtIndex:i] objectForKey:@"retweeted"] boolValue];
I am getting this error:
How to solve this problem?
source to share
After serialization with NSJSONSerialization
boolean value is stored as NSNumber
. If you look at the type it actually stores, it is __NSCFBoolean
, but it doesn't matter. NSNumber
is an abstract class that does not exist. The system stores the value with a specific class.
So,
NSNumber* boolean = [serializedDictionary valueForKey:@"boolValue"];
returns @0
for NO
and @1
for YES
. You can use this as a booleanValue by doing:
if(boolean.boolValue){
// ...
}
source to share