JTObjectMapping
JTObjectMapping copied to clipboard
"Yes" or specific string map to boolean type?
I have JSON like this
"login_success" : "Yes", "isAdult": "N", ...
and
I want to mapping the result to below property property BOOL bSuccess; property BOOL isAudlt;
currently, the result map to the NSString property and then call method if the string is "YES" , bSuccess = YES...
is there any easy way?
There's no way to automatically convert meaningful (but arbitrary) strings into BOOLs. However, you can use the mapping callback to handle this yourself quite easily.
- (void)didMapObjectFromJSON:(id<JTValidJSONResponse>)object {
NSString *loginSuccessString = object[@"login_success"];
NSString *isAdultString = object[@"isAdult"];
BOOL isLoginSuccessful = [loginSuccessString isEqualToString:@"Yes"];
BOOL isAdult = [isAdultString isEqualToString:@"isAdultString"];
}
You can write your own method to convert strings to BOOLs however you want, but be sure to handle the situation where the key may be missing.
Thanks @zcharter. You can also write your own stringToBoolean mapping class which conforms to JTValidMappingKey
and transform that string to your expected value.