Home > Mobile >  How to ignore empty list when serializing to json?
How to ignore empty list when serializing to json?

Time:03-10

I am trying to figure out how to serialize to a json object and skip serializing properties whose values are empty lists. I am not using Newtonsoft json

using System.Text.Json;
using System.Text.Json.Serialization;
using AutoMapper;

I have an object with a property.

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
[JsonPropertyName("extension")]
public List<Extension> Extension { get; set; }

When I try to serialize this object using the following

var optionsJson =   new JsonSerializerOptions
    {
    WriteIndented = true,
    IgnoreNullValues = true,
    PropertyNameCaseInsensitive = true,
    };

var json = JsonSerializer.Serialize(report, optionsJson);

It still gives me an empty array:

"extension": [],

Isn't there a way to keep it from serializing these empty lists? I would like to see extension gone. It should not be there at all. I need to do this because the gateway will respond with an error if I send:

"extension": null,

It must not be part of the object when serialized.

gateway error

The reason why I do not want these empty lists is that the third party gateway I am sending to objects to empty lists

"severity": "error", "code": "processing", "diagnostics": "Array cannot be empty - the property should not be present if it has no values", "location": [ "Bundle.entry[2].resource.extension", "Line 96, Col 23" ]

I'm trying to avoid doing some kind of nasty string replace on this.

CodePudding user response:

You can add a dummy property that is used during serialization that handles this.

  • Add a new property with the same signature, but flag it with JsonPropertyNameAttribute to ensure it is being serialized with the correct name, and also with the JsonIgnoreAttribute so that it will not be serialized when it returns null.
  • The original property you mark with JsonIgnore, unconditionally, so that it will never be serialized itself
  • This dummy property would return null (and thus be ignored) when the actual property contains an empty list, otherwise it would return that (non-empty) list
  • Writes to the dummy property just writes to the actual property

Something like this:

[JsonIgnore]
public List<Extension> Extensions { get; set; } = new();

[JsonPropertyName("extension")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
 public List<Extension> SerializationExtensions
    {
        get => Extensions?.Count > 0 ? Extensions : null;
        set => Extensions = value ?? new();
    }
  • Related