0

I am serializing a custom class in Objective-C using JSONModel. The class User that I am trying to serialize looks like:

<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>

There are a few nil values, but that's expected.

I am trying to serialize using the line:

id json = [self.currentUser toJSONString];

The JSON, when printed out is:

{
    "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"
}

The values that were nil have disappeared. Is there a way to have them marked as "null" when serializing ?

jscs
  • 63,694
  • 13
  • 151
  • 195
Ashish Agarwal
  • 14,555
  • 31
  • 86
  • 125
  • 3
    Have you marked these as ``?!? Otherwise, they will be included. Show us how you've defined the properties of your `User` class. – Rob Feb 12 '15 at 06:35

1 Answers1

0

As noted by Rob, it matters whether the property is marked as Optional or not.

If a property is marked as Optional, and the value is nil, the key is not outputted in the resulting JSON. If you remove the Optional flag, it will be outputted as null.

We are considering making a change such that when an Optional property is explicitly set as NSNull, the value will be outputted as null. See this issue - once it is resolved, you will be able to do the following:

self.currentUser.DeveloperDetails = [NSNull null];
NSString *json = [self.currentUser toJSONString];
Community
  • 1
  • 1
James Billingham
  • 760
  • 8
  • 32