[System.Text.Json] Conditionally ignore an open-generic type at the type level #122049
Unanswered
RenderMichael
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
We have a DTO to interface with an API where
nulland "missing property" are both meaningful while having different semantics.We have created a type to represent this,
Optional<T>, and we want to be able to create arbitrary properties with it without having to worry about JSON configuration.Implementation of Optional<T>.
Sample usage:
Functionally, we want to add
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]directly on theOptional<T>type; that however is not supported. We have to add that attribute to each property.A workaround we have considered is applying modifier to the serialization context with
WithAddedModifier. I have not figured out if we can make it work here (likely yes, with theJsonPropertyInfo.ShouldSerializemethod), but there are two more fundamental issues: we lose our strongly typed serialization context, and we cannot hand our type off to consumers to use out of the box. Both of these are non-starters.We have a mitigation which is admittedly not AOT-friendly (important for us): an
OptionalConverterFactorythat creates converters that throw whenWriteing adefault(Optional<T>), with a reminder to addWhenWritingDefaulton the property.We have tried to make the
Writemethod ignore the property entirely, but the closest we get is invalid json, eg.{ "viewport": }. Is there something we can to do un-write the property name there?Or, more broadly, is there some solution out there to make
Optional<T>work as expected without any other configuration?Beta Was this translation helpful? Give feedback.
All reactions