Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring null fields in Json.net

I have some data that I have to serialize to JSON. I'm using JSON.NET. My code structure is similar to this:

public struct structA {     public string Field1;     public structB Field2;     public structB Field3; }  public struct structB {     public string Subfield1;     public string Subfield2; } 

Problem is, my JSON output needs to have ONLY Field1 OR Field2 OR Field3 - it depends on which field is used (i.e. not null). By default, my JSON looks like this:

{     "Field1": null,     "Field2": {"Subfield1": "test1", "Subfield2": "test2"},     "Field3": {"Subfield1": null, "Subfield2": null}, } 

I know I can use NullValueHandling.Ignore, but that gives me JSON that looks like this:

{     "Field2": {"Subfield1": "test1", "Subfield2": "test2"},     "Field3": {} } 

And what I need is this:

{     "Field2": {"Subfield1": "test1", "Subfield2": "test2"}, } 

Is there simple way to achieve this?

like image 675
Thaven Avatar asked Mar 22 '12 09:03

Thaven


People also ask

How do you ignore NULL values in JSON response?

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.

How to ignore property in json response c# if null?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.

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.


1 Answers

Yes you need to use JsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore.

But because structs are value types you need to mark Field2, Field3 nullable to get the expected result:

public struct structA {     public string Field1;     public structB? Field2;     public structB? Field3; } 

Or just use classes instead of structs.

Documentation: NullValueHandling Enumeration

like image 186
nemesv Avatar answered Nov 15 '22 15:11

nemesv