Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore Null Values When Serializing JSON

Is it possible to serialize an object to JSON but only those properties with data?

For example:

public class Employee
{
   [JsonProperty(PropertyName = "name")]
   public string Name { get; set; }

   [JsonProperty(PropertyName = "id")]
   public int EmployeeId { get; set; }

   [JsonProperty(PropertyName = "supervisor")]
   public string Supervisor { get; set; }
}

var employee = new Employee { Name = "John Doe", EmployeeId = 5, Supervisor = "Jane Smith" };

var boss = new Employee { Name = "Jane Smith", EmployeeId = 1 };

The employee object will be serialized as:

 { "id":"5", "name":"John Doe", "supervisor":"Jane Smith" }

The boss object will be serialized as:

 { "id":"1", "name":"Jane Smith" }

Thanks!

like image 463
cksanjose Avatar asked May 10 '14 04:05

cksanjose


Video Answer


1 Answers

You could do something like this on your JSON properties:

[JsonProperty("property_name", NullValueHandling = NullValueHandling.Ignore)]

Alternatively you can ignore null values when you serialize.

string json = JsonConvert.SerializeObject(employee, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
like image 173
David DeMar Avatar answered Oct 02 '22 01:10

David DeMar