Skip to content

[JsonSerializer] Provide option to specify a custom default value for a type, property, or field #36236

Closed as not planned

Description

@layomia

#779 discusses options to ignore CLR default values during serialization (API approved).

Rather than using the CLR default, users may want to specify a custom default to be ignored. This issue is a placeholder for an API proposal to make this achievable.

Activity

  1. added this to the 5.0 milestone on May 11, 2020
  2. self-assigned this
    on May 11, 2020
  3. removed
    untriagedNew issue has not been triaged by the area owner
    on May 11, 2020
  4. modified the milestones: 5.0.0, Future on Jun 20, 2020
  5. layomia commented on Sep 1, 2020

    @layomia
    ContributorAuthor

    From @steveoh in #41630

    Description

    // startup
    .AddJsonOptions(options => {
      options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
      options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull & JsonIgnoreCondition.WhenWritingDefault;
      options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
    });
    
    // ...
    
    [DefaultValue(typeof(decimal), "-1")]
    [DefaultValue(-1.0)]
    [DefaultValue(-1D)]
    public double Prop { 
    	get => _prop;
        set => _prop = Math.Round(value, 2);
    }

    When the prop is set to -1, which is the default value, the property is serialized when JsonIgnoreCondition.WhenWritingDefault is set. I would expect that property to not be serialized.

    Configuration

    osx catalina x64
    5.0.100-preview.8.20417.9

  6. walterpg commented on May 19, 2021

    @walterpg

    Raising the flag

    FYI, I am considering returning to a tried-and-true third party to get this functionality. Custom JsonConverters are not sustainable workarounds for my scenarios.

  7. eiriktsarpalis commented on Oct 15, 2021

    @eiriktsarpalis
    Member

    Might need to be considered in conjunction with this proposal: #55781 (comment)

  8. eiriktsarpalis commented on Oct 26, 2021

    @eiriktsarpalis
    Member

    Also related #593 and #40395.

  9. eiriktsarpalis commented on Sep 2, 2022

    @eiriktsarpalis
    Member

    I believe that most of that functionality can now be achieved using a combination of the JsonPropertyInfo.ShouldSerialize/Get/Set delegates in the contract customization layer. There a limits to what values can be specified in the attribute layer, so I'd be inclined to close this in favor of the API surface exposed in #63686.

  10. ghost locked as resolved and limited conversation to collaborators on Oct 2, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions