Diego Barros
Diego Barros

Reputation: 2068

RESTKit object BOOL property to true/false JSON

I have some objects which I'm sending to a server as JSON, in the request body, for a POST request. My question relates to boolean properties.

Say I have this property in an object I'm sending as JSON:

@property (nonatomic) BOOL exported;

By default, RestKit sends the boolean as either 1 or 0 in JSON. How can I setup RestKit so that all BOOLs are sent as true or false (which is the JSON boolean type).

Funnily enough, when going the other way, from JSON true or false to the BOOL property, RestKit reads the JSON true/false just fine, appropriately setting the property.

Upvotes: 7

Views: 3344

Answers (4)

Milan Nosáľ
Milan Nosáľ

Reputation: 19737

If anybody uses RestKit with Swift, and has some trouble with it as I did, do not forget to add dynamic modifier to the property, and the Bool variable cannot be optional. Therefore use following:

dynamic var exported: Bool = false

Check question: Bool Property Cannot be marked dynamic in swift

Upvotes: 0

ender44
ender44

Reputation: 31

Alternatively; you could make it a bool instead of a BOOL and restkit will parse it properly.

@property (nonatomic) bool exported;

The reason it handles it properly in a read is that bool's are inherently just 1 or 0... so Restkit is smart enough to convert it to a BOOL.

Upvotes: 2

Diego Barros
Diego Barros

Reputation: 2068

This problem stems from the fact that SQLite does not have a boolean data type. So if I have a Boolean in my Core Data schema, it still ends up being stored as an integer in SQLite (with an int value of 1 or 0). So that's why I am seeing either 1 or 0 when outputting JSON via RestKit.

To correct this, I changed my property from my original question from BOOL to NSNumber:

@property (nonatomic) NSNumber *exported;

Whenever I assign to this property I need to set it with an NSNumber boolean value.

   target.exported = [NSNumber numberWithBool:[self.exported boolValue]];

The JSON generated is now correct, because I am setting the NSNumber with boolValue:

"exported" : true

Upvotes: 1

Lithu T.V
Lithu T.V

Reputation: 20021

Source type :NSCFBoolean 
Destination type : NSString
Discussion: Boolean literals true and false parsed from JSON are mapped to NSString properties as @"true" and @"false"

Source :See This table

Upvotes: 1

Related Questions