Question

I need to deal with JSON data with arbitrary structures in iOS.

However, NSJSONSerialization convert true/false value into NSNumber.

So my question is, how can I tell when a NSNumber is converted from a boolean value true/false, as apposed to actual number 0/1?

Note: I am aware of [NSNumber numberWithBool], but here, I want to figure out when it's appropriate to call it. I'm also aware that writing my own parser solves this problem, but I want to make sure there isn't a easier solution before I go done that route.

Was it helpful?

Solution

The solution is:

if ([parsedValue isKindOfClass [NSNumber class]] &&
    strcmp([parsedValue objCType], @encode(char)) == 0) {
    // parsedValue is converted from 'true' or 'false' in JSON.
}

One weird thing is NSJSONSerielization sets objCType of a boolean value to @encode(char) instead of @encode(BOOL).

OTHER TIPS

In fact you can't know if an NSNumber "was" a boolean. But no matter call boolValue and if it was boolean value you will get the right value. If it was a number you get true for all value except 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top