Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
layomia opened this issue May 11, 2020 · 5 comments
Assignees
Milestone

Comments

@layomia
Copy link
Contributor

layomia commented May 11, 2020

#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.

@layomia
Copy link
Contributor Author

layomia commented Sep 1, 2020

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

@walterpg
Copy link

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.

@eiriktsarpalis
Copy link
Member

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

@eiriktsarpalis
Copy link
Member

Also related #593 and #40395.

@eiriktsarpalis
Copy link
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.

@eiriktsarpalis eiriktsarpalis closed this as not planned Won't fix, can't repro, duplicate, stale Sep 2, 2022
@ghost ghost locked as resolved and limited conversation to collaborators Oct 2, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants