Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore a property in class if null, using json.net

Tags:

c#

json.net

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.

like image 942
Amit Avatar asked Jun 28 '11 14:06

Amit


People also ask

How do I ignore JSON property if null?

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.

Which of the following attributes are required to ignore properties for JSON serializer?

To ignore individual properties, use the [JsonIgnore] attribute.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


Video Answer


1 Answers

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.

like image 154
sirthomas Avatar answered Sep 21 '22 08:09

sirthomas