Skip to content

System.Text.Json option to ignore default values during serialization #779

@karthickthangasamy

Description

@karthickthangasamy

Updated by @layomia. I'm pasting the API approved in #35649, along with API review notes. An option to ignore defaults on deserialization was not added, as we couldn't identify a reasonable scenario that requires this. This proposal does not include a way to specify a custom default. This is discussed in #36236.

Video

  • Looks great. Only suggestion is to change WhenWritingDefaultValues to WhenWritingDefault.
  • JsonSerializerOptions.DefaultIgnoreCondition should throw ArgumentException rather than InvalidOperationException
namespace System.Text.Json.Serialization
{
    public enum JsonIgnoreCondition
    {
        Never = 0,
        Always = 1,
        WhenWritingDefault = 2
    }    
}

namespace System.Text.Json
{
    public partial class JsonSerializerOptions
    {
        public JsonIgnoreCondition DefaultIgnoreCondition { get; set; } = JsonIgnoreCondition.Never;
    }
}
Original proposal (click to view)

There is no option to ignore the DefaultValues for the properties in System.Text.Json.

The JSON.NET contains this options to ignore default values.

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DefaultValueHandling.htm

Usecase scenario:

For updating the Blazor component model, need to send the values which has only changes to component and refresh the UI, even for initial rendering of component itself, we will the default values.

return JsonSerializer.ToString(this, this.GetType(), new JsonSerializerOptions
{
     IgnoreNullValues = true,
     WriteIndented = true                
});

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions