简体   繁体   中英

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.

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.

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

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

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

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