stevo
stevo

Reputation: 2284

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

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.

Upvotes: 9

Views: 5345

Answers (4)

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"}
}

Upvotes: 2

hanorine
hanorine

Reputation: 7825

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.

Upvotes: 0

byczu
byczu

Reputation: 43

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

Upvotes: 2

Gökten Karadağ
Gökten Karadağ

Reputation: 136

I think this can be help

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

Upvotes: 2

Related Questions