I am using Json.NET to serialize a class to JSON.
I have the class like this:
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; }
}
I want to add a JsonIgnore()
attribute to Test2List
property only when Test2List
is null
. If it is not null then I want to include it in my json.
Similar to @sirthomas's answer, JSON.NET also respects the
EmitDefaultValue
property onDataMemberAttribute
:This may be desirable if you are already using
[DataContract]
and[DataMember]
in your model type and don't want to add JSON.NET-specific attributes.An adaption to @Mrchief's / @amit's answer, but for people using VB
See: "Object Initializers: Named and Anonymous Types (Visual Basic)"
https://msdn.microsoft.com/en-us/library/bb385125.aspx
As per James Newton King: If you create the serializer yourself rather than using JavaScriptConvert there is a
NullValueHandling
property which you can set to ignore.Here's a sample:
Alternatively, as suggested by @amit
An alternate solution using the
JsonProperty
attribute:As seen in this online doc.
You can write:
[JsonProperty("property_name",DefaultValueHandling = DefaultValueHandling.Ignore)]
It also takes care of not serializing properties with default values (not only null). It can be useful for enums for example.
As can be seen in this link on their site (http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size.aspx) I support using [Default()] to specify default values
Taken from the link