Problem
To serialize a class to JSON, I’m using Json.NET.
This is how my class looks:
class Test1
{
[JsonProperty("id")]
public string ID { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("url")]
public string URL { get; set; }
[JsonProperty("item")]
public List<Test2> Test2List { get; set; }
}
Only when Test2List is nil, I want to add a JsonIgnore() attribute to Test2List. I want to add it in my json if it isn’t null.
Asked by Amit
Solution #1
Another option is to use the JsonProperty attribute:
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
// or
[JsonProperty("property_name", NullValueHandling=NullValueHandling.Ignore)]
// or for all properties in a class
[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]
As can be seen in this internet document.
Answered by sirthomas
Solution #2
According to James Newton King, there is a NullValueHandling attribute that you can set to ignore if you write the serializer yourself rather than using JavaScriptConvert.
Here’s a sample:
JsonSerializer _jsonWriter = new JsonSerializer {
NullValueHandling = NullValueHandling.Ignore
};
Alternatively, as @amit mentioned,
JsonConvert.SerializeObject(myObject,
Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
Answered by Mrchief
Solution #3
If you don’t want to add Newtonsoft-specific characteristics to your mod, JSON.NET respects the EmitDefaultValue parameter on DataMemberAttribute.
[DataMember(Name="property_name", EmitDefaultValue=false)]
Answered by Tobias J
Solution #4
[JsonProperty(“property name”,DefaultValueHandling = DefaultValueHandling.Ignore)] is an example.
It also ensures that attributes with default values are not serialized (not only null). Enums, for example, can benefit from it.
Answered by Vatsal Patel
Solution #5
This allows you to disregard all nulls in an object while serializing it, and any null properties won’t appear in the JSON output.
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
var myJson = JsonConvert.SerializeObject(myObject, settings);
Answered by Chris Halcrow
Post is based on https://stackoverflow.com/questions/6507889/how-to-ignore-a-property-in-class-if-null-using-json-net