72

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?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Thaven
  • 1,857
  • 3
  • 19
  • 35
  • Possible duplicate of [How to ignore a property in class if null, using json.net](http://stackoverflow.com/questions/6507889/how-to-ignore-a-property-in-class-if-null-using-json-net) – Michael Freidgeim Aug 12 '16 at 08:20
  • Because you are using `struct`s, the only field that may have a null value is Field1. If you want Field2 and Field3 to be nulllable, you need to make them reference types instead of value types. – Suncat2000 Aug 16 '21 at 15:07

2 Answers2

80

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

James Newton-King
  • 48,174
  • 24
  • 109
  • 130
nemesv
  • 138,284
  • 16
  • 416
  • 359
77

You can also apply the JsonProperty attribute to the relevant properties and set the null value handling that way. Refer to the Reference property in the example below:

Note: The JsonSerializerSettings will override the attributes.

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

    public string Name { get; set; }
}
SuperStormer
  • 4,997
  • 5
  • 25
  • 35
Jaans
  • 4,598
  • 4
  • 39
  • 49