简体   繁体   中英

How to get boolean value from JSON?

Suppose this is a value in a JSON I want to assign to a BOOL variable:

"retweeted": false

Here is how I parse 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 the JSON:

tweet.retweeted = [[[timeline objectAtIndex:i] objectForKey:@"retweeted"] boolValue];

I get this error:

在此处输入图像描述

How to solve this problem?

My preferred way of doing it is:

BOOL success = [[responseObject valueForKey:@"success"] boolValue]

Clean, succinct and inline.

BOOL *retweeted;

this is wrong, booleans are scalars, not Objective-C objects, so they don't need to be declared as pointers. Use

BOOL retweeted;

instead.

After serialization with NSJSONSerialization the boolean is stored as an NSNumber . If you look at the type it actually stores is is a __NSCFBoolean but that does not matter. NSNumber is an abstract class that does not exist. The system stores the value with a concrete class.

So

NSNumber* boolean = [serializedDictionary valueForKey:@"boolValue"];

this returns a @0 for NO and @1 for YES . You can use is as a booleanValue by doing:

if(boolean.boolValue){
  // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM