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:

enter image description here

How to solve this problem?

+3


source to share


3 answers


BOOL *retweeted;

      

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



BOOL retweeted;

      

instead.

+13


source


My preferred way of doing this:

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



Clean, concise and built in.

+10


source


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){
  // ...
}

      

+7


source







All Articles