简体   繁体   English

Json在objective-c中解析nil字段

[英]Json parsing nil field in objective-c

I have a problem with mapping a JSON to a foundation object... 我将JSON映射到基础对象时遇到问题...

Is there any way to put a "nil" value to a class member variable when the JSON string doesn't contain that key? 当JSON字符串不包含该键时,有没有办法将“nil”值放到类成员变量上?

Ex, here's my DataModel class: 例如,这是我的DataModel类:

@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. 该类用于解析ClientModel对象中有关客户端的一些信息,并具有ErrorCode和Status字段。

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. 如果json包含“Error”作为状态,则下一个字段是ErrorCode。

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). 问题是服务器不会总是向我发送ErrorCode的键值(当状态为“Ok”时,服务器API不发送ErrorCode键值)。

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? 考虑到我无法修改服务器发送的JSON,如何解析我的模态对象中收到的JSON字符串,并在JSON字符串不包含时将“nil”作为ErrorCode值?

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. 我目前正在使用JSONModel,但是当缺少密钥时,它给出了“传入数据无效”错误。 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. 我知道用于java的Jackson API处理这种情况,但我不知道在Objective-C中是否有类似的东西。 If I can do a workaround with NSJSONSerialization I would be glad to hear it, too. 如果我可以使用NSJSONSerialization进行解决方法,我也很高兴听到它。

Thanks! 谢谢!

Looks like JSONModel declares a protocol called "Optional" which is intended for exactly this use. 看起来像JSONModel声明了一个名为“Optional”的协议 ,它正是为了这个用途。 Declare the property that might not be present in the JSON as conforming to this protocol to make the initializer not error: 声明JSON中可能不存在的属性符合此协议,以使初始化程序不会出错:

@property (strong, nonatomic) NSString<Optional> * ErrorCode;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM