Question

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!

Was it helpful?

Solution

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 });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top