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.
You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.
To ignore individual properties, use the [JsonIgnore] attribute.
SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.
An alternate solution using 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 seen in this online doc.
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