Home > database >  How to ignore JSON property basing on the other property value in .NET using System.Text.Json serial
How to ignore JSON property basing on the other property value in .NET using System.Text.Json serial

Time:02-01

I am having an exemplary .NET class:

public class Foo
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Is it possible to serialize Name property only if Age is > 18 using JsonSerializer.Serialize(...) method? Would it be possible to achieve such behaviour without implementing custom serializer, eg. using some attributes? Thanks in advance for any help.

CodePudding user response:

You can either write custom converter for the type or use .NET 7 approach with customizing contract:

var foos = new[] { new Foo { Age = 1, Name = "Should not show" }, new Foo { Age = 19, Name = "Name" } };

var result = JsonSerializer.Serialize(foos, new JsonSerializerOptions
{
    TypeInfoResolver = new DefaultJsonTypeInfoResolver
    {
        Modifiers = { SkipUnderagedName }
    }
});

Console.WriteLine(result); // prints "// [{"Age":1},{"Name":"Name","Age":19}]"

static void SkipUnderagedName(JsonTypeInfo ti)
{
    if (ti.Type.IsAssignableTo(typeof(Foo)))
    {
        var prop = ti.Properties.FirstOrDefault(p => p.Name == nameof(Foo.Name));
        if (prop is not null)
        {
            prop.ShouldSerialize = (obj, _) =>
            {
                var foo = obj as Foo;
                return foo?.Age >= 18;
            };
        }
    }
}

CodePudding user response:

Since you don't want any custom serializers your can try this code. It returns Name property value eguals null if Age < 19. When Name is null, serializer ignores this property.

public class Foo
{
    private string _name;

    [System.Text.Json.Serialization.JsonPropertyName("Name")]
    [System.Text.Json.Serialization.JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
    public string _Name
    {
        get { return Age > 18 ? _name : null; }
        set { _name = value; }
    }

    [System.Text.Json.Serialization.JsonIgnore]
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    public int Age { get; set; }
}
  • Related