我使用JSONModel在Objective-C中序列化自定义类。我尝试序列化的类User
如下所示:
<User>
[UserCount]: 658
[CreationDate]: 2014-04-17T00:38:34.176Z
[Credits]: 0
[Email]: Email Address
[Locale]: <nil>
[DeveloperDetails]: <nil>
[Name]: ashishagarwal
[UserName]: ashishagarwal
[_id]: xxxxxxxx--userid--------------
[FirstName]: First Name
[AuthenticationType]: <nil>
[_deleted]: 0
[LastActivityDate]: 2015-02-10T23:26:41.816Z
[Type]: 0
[IsAuthenticated]: 0
[LastName]: Last Name
[LastLoginDate]: 2015-02-12T03:39:50.626Z
</User>
有一些nil
值,但这是预期的。
我正在尝试使用该行序列化:
id json = [self.currentUser toJSONString];
JSON打印出来时是:
{
"UserCount": 658,
"CreationDate": "2014-04-17T00:38:34.176Z",
"Credits": 0,
"Email": "Email Address",
"Name": "ashishagarwal",
"UserName": "ashishagarwal",
"_id": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
"FirstName": "First Name",
"_deleted": false,
"LastActivityDate": "2015-02-10T23:26:41.816Z",
"Type": 0,
"IsAuthenticated": false,
"LastLoginDate": "2015-02-12T03:39:50.626Z",
"LastName": "Last Name"
}
nil
的值已消失。有没有办法在序列化时将它们标记为“null”?
答案 0 :(得分:0)
As noted by Rob,该属性是否标记为Optional
非常重要。
如果属性标记为Optional
,且值为nil
,则不会在生成的JSON中输出密钥。如果您删除Optional
标记,则会将其输出为null
。
我们正在考虑进行更改,以便在Optional
属性明确设置为NSNull
时,该值将输出为null
。 See this issue - 一旦解决,您将能够执行以下操作:
self.currentUser.DeveloperDetails = [NSNull null];
NSString *json = [self.currentUser toJSONString];