Reputation: 461
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!
Upvotes: 16
Views: 36673
Reputation: 1
For those not wanting to use the Newtonsoft.Json
Package and instead want to use the System.Text.Json.Serialization
Package, you can alternatively use this:
[JsonPropertyName("foo")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? Foo { get; set; }
JsonIgnoreCondition Documentation
Upvotes: 0
Reputation: 2660
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 });
Upvotes: 49