9

I have JSON that I am getting back that potentially gets back nulls as part of the values. How can I, or is there even a way, to exclude those nulls from the collection?

      {
     "id": "5551212",
     "from": {
        "name": "Message creator",
        "start_time": "2011-10-21T22:00:00",
        "end_time": "2011-10-23T17:00:00",
        "location": "area 51",
        "id": "2121212122"
     },
     "to": {
        "data": [
          {
              "name": "Jay-Z",
              "id": "77777"
           },
           {
              "name": "Bill Murray",
              "id": "88888"
           },
           null,
           {
              "name": "Anthony Hopkins",
              "id": "99999"
           }
        ]
     },
     "message": "Some message from somewhere",
     "updated_time": "2011-09-19T23:53:51+0000",
     "unread": 1,
     "unseen": 0
  }

Notice between Bill Murray and Anthony Hopkins the null that is returned. Thanks.

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
Conway Stern
  • 135
  • 2
  • 6
  • Null has no meaning now? News to me! – leppie Jan 24 '12 at 16:07
  • I never said that null didn't have meaning. According to the API here (http://james.newtonking.com/projects/json/help/html/M_Newtonsoft_Json_JsonConvert_DeserializeObject__1_2.htm) you can pass settings to include or ignore nulls. So based on that, there should be a mechanism to exclude them. – Conway Stern Jan 24 '12 at 16:17
  • @leppie not serializing null or empty arrays will reduce document size in nosql databases, so yeah its kinda important – Korayem Feb 22 '12 at 13:35

2 Answers2

12

You can simply decorate properties/fields that can be null with

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; set; }

For more info on how to reduce json size: http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size.aspx

Korayem
  • 12,108
  • 5
  • 69
  • 56
  • I will give this a try. Will up vote once I get working. – Conway Stern Mar 08 '12 at 18:52
  • Sure thing. It's the recommended way as per the author himself as mentioned in the blog post – Korayem Mar 09 '12 at 14:07
  • 1
    You can also set the null value handling on a wider scale by changing the property on `SerializerSettings`. For example, on Web API you might do: `config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore` in your `WebApiConfig` class. – Nick Jan 16 '15 at 00:20
-4

I would use convert method to get an XML string.

// jsonString is populated from your....
XmlNode xmlNode = JsonConvert.DeserializeXmlNode(jsonString);

The null value in XML would be like:

...<data></data>...

which can be easily removed by string replacement or XML filtering.

Ray Hayes
  • 14,896
  • 8
  • 53
  • 78
David.Chu.ca
  • 37,408
  • 63
  • 148
  • 190