When using json.net to convert the object to JSON, it may need to exclude the attribute with value to NULL. This is especially useful when some attributes should be included in serialized output only when they have non -empty values.
Custom attribute processing
In order to control how to handle the attributes of vacant values during the serialization, JSON.NET provides the JSONPROPRTY attribute. By setting the NullValueHandling property of this attribute to NullValueHandling.Ignore, you can prevent the attribute from containing the situation of NULL in the JSON output.
For example, in the provided example, you can add the following code to TEST1:
Through this adjustment, it is included in JSON representation only when Test2List contains non -empty values. If Test2List is NULL, it will completely ignore it.
<code class="language-csharp">[JsonProperty("test2_list", NullValueHandling = NullValueHandling.Ignore)] public List<test2> Test2List { get; set; }</code>
In addition to the JSONPROPERTY attribute, JSON.NET also provides a JSONObject attribute that can be applied to a class to configure all attributes during the serialization period. Set the ItemnullValueHandling property of JSONOBJECT to NULLVALUEHANDLING.IGNORE can be achieved as the results of using the same attributes to apply nullValuehandling.ignore to the use of JSONPROPERTY.
The above is the detailed content of How Can I Ignore Null Properties When Serializing JSON with Json.NET?. For more information, please follow other related articles on the PHP Chinese website!