What is the equivalent of Newtonsoft.Json DefaultValueHandling = DefaultValueHandling.Ignore option in System.Text.Json

Viewed 2710

I'm migrating from Newtonsoft.Json to System.Text.Json in my .NET Core 3.0 application.

How do I get have the same behaviour with System.Text.Json as I have in my .NET Core 2.2 app with Newtonsoft.Json configured with DefaultValueHandling = DefaultValueHandling.Ignore? You can find the DefaultValueHandling option described here.

4 Answers

I don't think you can do this, at least not in an easy way. You can easily ignore null values using IgnoreVullValues property of JsonSerializerOptions class but this will only ignore null values and still serialize integers, booleans etc. with default values. You can find more about JsonSerializerOptions class here

Please try this library I wrote as an extension to System.Text.Json to offer missing features: https://github.com/dahomey-technologies/Dahomey.Json.

You will find support for ignoring default values:

using Dahomey.Json;
using Dahomey.Json.Attributes;
using System.Text.Json;

public class ObjectWithDefaultValue
{
    [JsonIgnoreIfDefault]
    [DefaultValue(12)]
    public int Id { get; set; }

    [JsonIgnoreIfDefault]
    [DefaultValue("foo")]
    public string FirstName { get; set; }

    [JsonIgnoreIfDefault]
    [DefaultValue("foo")]
    public string LastName { get; set; }

    [JsonIgnoreIfDefault]
    [DefaultValue(12)]
    public int Age { get; set; }
}

Setup json extensions by calling on JsonSerializerOptions the extension method SetupExtensions defined in the namespace Dahomey.Json: Then serialize your class with the regular Sytem.Text.Json API:

public void Test()
{
    JsonSerializerOptions options = new JsonSerializerOptions();
    options.SetupExtensions();

    ObjectWithDefaultValue obj = new ObjectWithDefaultValue
    {
        Id = 13,
        FirstName = "foo",
        LastName = "bar",
        Age = 12
    };

    string json = JsonSerializer.Serialize(obj, options); // {"Id":13,"LastName":"bar"}
}

I think this can be help

services.AddMvc().AddJsonOptions(options => options.JsonSerializerOptions.IgnoreNullValues = true);

There is a proposed api-suggestion #42635 for ignoring default values that has been added to .NET Core 5.0 release due out in November 2020. Newtonsoft currently is the only supported solution worth using for this particular issue.

Related