Ignoring null fields in Json.net

I have some data that I have to serialize to JSON. I am using JSON.NET. My code structure looks like this:

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

The problem is that my JSON output should ONLY have Field1 OR Field2 OR Field3 - it depends on which field is used (that is, not empty). 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 this gives me JSON, which looks like this:

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

And I need this:

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

Is there an easy way to achieve this?

+54
json c # serialization
Mar 22 2018-12-12T00:
source share
2 answers

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

But since 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

+58
Mar 22 2018-12-12T00:
source share

You can also apply the JsonProperty attribute to the corresponding properties and thus configure the processing of null values. Refer to the Reference property in the following example:

Note. JsonSerializerSettings override attributes.

 public class Person { public int Id { get; set; } [JsonProperty( NullValueHandling = NullValueHandling.Ignore )] public int? Reference { get; set; } public string Name { get; set; } } 

Hth.

+51
Feb 26 '14 at 11:14
source share



All Articles