System.Text.Json : Consider supporting F# discriminated unions #55744
Description
Concerning support for discriminated unions, it might be worth pointing out that there is no one canonical way to encode DUs in JSON. DUs are used in many different ways in F# code, including the following:
- Single case DUs, e.g.
type Email = Email of string
, used to provide a type-safe wrapper for common values. A user might expect thatEmail("email")
should serialize as its payload,"email"
. - Type-safe enums, e.g.
type Suit = Heart | Spade | Diamond | Club
. Users might reasonably expect thatSpade
should serialize as the union case identifier,"Spade"
. - Unions with arbitrary combinations of union cases and arities, e.g.
type Shape = Point | Circle of radius:float | Rectangle of width:float * length:float
. A value likeCircle(42.)
would require an encoding similar to{ "shape" : "circle", "radius" : 42 }
. Users should be able to specify the case discriminator property name ("shape"
) as well as the identifier for the union case (Circle
mapping to"circle"
).
In light of the above, I'm increasingly starting to think that System.Text.Json should not be providing a default mechanism for serializing DUs. Users would still be able to use available custom converters that provide the union encoding that suits their use case or perhaps use unions in their data contracts in a way that bypasses the serialization layer altogether.
Originally posted by @eiriktsarpalis in #29812 (comment)
If we do decide to support F# DUs in the future, it would likely be in the form of a publicly available converter factory à la JsonStringEnumConverter that configures one or more of the above alternative serialization formats.
Activity