Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get json.net to exclude nulls when deseralizing a collection? [duplicate]

Tags:

json

c#

json.net

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.

like image 587
Conway Stern Avatar asked Jan 24 '12 16:01

Conway Stern


1 Answers

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

like image 137
Korayem Avatar answered Oct 05 '22 22:10

Korayem