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!
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With