Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json parsing nil field in objective-c

I have a problem with mapping a JSON to a foundation object...

Is there any way to put a "nil" value to a class member variable when the JSON string doesn't contain that key?

Ex, here's my DataModel class:

@interface DataModel : JSONModel

@property (strong, nonatomic) NSString* Status;
@property (strong, nonatomic) NSString* ErrorCode;

@property (strong, nonatomic) ClientModel* Client;

@end

That class is used to parse some information about the client in the ClientModel object and has a ErrorCode & Status field.

Status field can contains either "Ok" or "Error". No problem here. the next field is an ErrorCode in case the json contained "Error" as the status.

The problem is that the server won't always send me a key-value for ErrorCode (When the Status is "Ok", the server API doesn't send the ErrorCode key-value).

Considering the fact that I cannot modify the JSON sent by the server, how can parse the JSON string received in my modal object and put "nil" as the ErrorCode value when the JSON string doesn't contain it?

Is there any library that allow us to do this? I'm currently using JSONModel, but it gives me an "Incoming data was invalid" error when keys are missing. I know Jackson API for java handle this kind of situation, but I'm not aware if there's something like that in Objective-C. If I can do a workaround with NSJSONSerialization I would be glad to hear it, too.

Thanks!

like image 981
Shinnyx Avatar asked Dec 05 '25 19:12

Shinnyx


1 Answers

Looks like JSONModel declares a protocol called "Optional" which is intended for exactly this use. Declare the property that might not be present in the JSON as conforming to this protocol to make the initializer not error:

@property (strong, nonatomic) NSString<Optional> * ErrorCode;
like image 50
jscs Avatar answered Dec 08 '25 10:12

jscs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!