Repository navigation
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 thatSpadeshould 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 (Circlemapping 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
[-]Consider supporting F# discriminated unions[/-][+]System.Text.Json : Consider supporting F# discriminated unions[/+]eiriktsarpalis commentedon Jul 15, 2021
Tagging @bartelink @Zaid-Ajaj @NinoFloris who might have opinions on the matter.
Zaid-Ajaj commentedon Jul 15, 2021
IMO just because there are multiple ways to represent DUs in JSON doesn't imply that a library shouldn't pick a default. I think many F# devs would appreciate a choice that works out of the box with the possibility of customization where required, not having to customize or having to understand library internals to get started with it.
This is the approach I implemented in
Fable.Remoting.Jsonwhich is a Newtonsoft.Json converter for F# types without loss of information (possible to round trip). Given aShapetype likeThe following JSON is generated
of course there could be a setting to choose to write out the property names when provided
bartelink commentedon Jul 15, 2021
I agree [with the OP] that there cannot and should not be a default canonical implementation; As
FSharp.SystemTextJsonand the default encoding provided byNewtonsoft.Json>=6 illustrate, there are many choices for how to represent things, and there is no reasonable default IMO.I tend to take view that individual converters that do easy to describe things are the way to go. Thus I would ideally like to see the following in the box:
TypeSafeEnumConverter: example unoptimized implUnionConverter: IME the format you proposed in the OP ({ "discriminator": "value", <named fields from case as for a class/record, same for cases in tupled form> }) is common in the wild, and IME there are established implementations on the JVM, Swift and JS which work with that rendering format). See FsCodecUnionConverterimpl. (There's also an OSS equivalent of this converter forNewtonsoft.Jsonthat implements this scheme)bartelink commentedon Jul 15, 2021
While
Newtonsoft.Jsondoes this out of the box, I'd be very much against having this representation be a default. Furthermore, I think its a harmful thing to even put in the box in the first place; let me try to justify this:In order to guard against things that IME happen in the wild, I'd propose the following rules:
Itemfields)Again, IME, maintaining symmetry is valuable for nullary cases too. The main reason for this being that any consumer will be able to adapt to me adding a field to the case payload if it's rendered as
{ "shape": "point"}; one is simply adding a field to an object, versus transitioning from astringto anobject.I'd also mention another reason a canonical default handing is likely to run aground even if it was to be defined:
JObjector equivalent (see UnionConverter Unknown case support)jhf commentedon Jul 23, 2021
I agree with @bartelink that the compatibility of json encoded data can be a minefield, that requires attention when writing migrations, and when making API changes.
I still think that having a default canonical implementation provides a good user experience. I think it is too early to force the programmer understand and choose between serialisation strategies just because they wish to turn information into JSON.
Rather, when somebody has durable data, or needs to concern themselves with wire compatibility, then the way things are serialised may get important. In my case, when I upgrade durable data migrations, I transform the data, using the default canonical implementation, but I map from one type to another type, and write again using the default canonical implementation.
For exposed API REST/json endpoints I either make sure it is a wire compatible change, or I make a new endpoint (probably with a version number).
If there is a large number of types involved, then the burden of having to specify a per type serialisation strategy, as a lot of extra work. Surely, yes, it will be more optimised, and possible upgrade proof, but since I'm writing migrations and making new endpoints, that point is moot, for me. Thus I'm forced to do more work, without any apparent benefit.
By having a default canonical implementation, and allowing overrides, it is possible to use json with a minimum amount of effort, and allow freedom when it has benefit.
By the way, what would be the developer experience when using Type Providers, such as https://fsprojects.github.io/SQLProvider/ when there is no default canonical implementation?
From my perspective, having a default canonical implementation, allows usage without con
@bartelink
15 remaining items
KenBonny commentedon Feb 14, 2024
Is this still being investigated and worked on? As I'm quite interested in seeing STJ support F# DU's.
eiriktsarpalis commentedon Feb 14, 2024
It is not being worked on currently. We will update this issue as soon as something changes.
YkTru commentedon Apr 2, 2024
@eiriktsarpalis
1- Do you think it will ever be possible? I mean, should we keep hope or do all by hand?
2- While waiting: Would you recommend Wlaschin DTO approach?
2a- Else what would be your recommend, preferred approach in most cases?
Thank you
bartelink commentedon Apr 2, 2024
@YkTru why do it by hand when there are two perfectly viable answers to 2a:
FSharp.SystemTextJsonhas a dramatically more complete implementation that has every conceivable rendition format (its a much larger project though)eiriktsarpalis commentedon Apr 2, 2024
Using a third-party option is perfectly fine. One thing to note about any custom converter is that it necessarily loses the ability to do streaming serialization (only because streaming converters are internal for now).
In other words, attempting to serialize something large like
would necessarily result in the entire payload being buffered by the serializer. That shouldn't matter much as long as you're restricted to small-ish values.
rynoV commentedon Apr 11, 2025
It seems like using a third-party option is the current recommendation for F# discriminated unions with STJ, so I wanted to bring up a potential area for improvement on the first-party side to make that work better:
Problem
When passing a discriminated union value with
objecttype toJsonSerializer.Serialize,JsonConverterattributes (e.g.UnionConverterfromFsCodec) on F# discriminated unions won't be resolved, and it will fail withSystem.NotSupportedException: F# discriminated union serialization is not supported.Affected areas
This situation occurs unavoidably in ASP.NET (see dotnet/aspnetcore#51481 which was closed deferring to this issue) and SignalR.
Cause
The issue seems to be that
GetTypeis used to resolve the converter for the DU value, and for a DU instantiation,GetTypereturns the internal generated subclass for that case, and so theJsonConverterattribute registered on the base class is not picked up.Potential fix
It seems like it would be possible to fix this in STJ by adding a special case for F# discriminated union instances to resolve their type info using the base class. It doesn't seem like resolving type info for the generated subclasses makes sense because the user has no control over these (also meaning it shouldn't be a breaking change?).
Related issue in FsCodec which discusses a workaround: jet/FsCodec#128
kerams commentedon May 9, 2025
The problem with this is that while FSTJ
JsonSerializerOptionswith the source generated serialization context assigned to theTypeInfoResolverproperty appears to work withJsonSerializerIsReflectionEnabledByDefaultdisabled, reflection is still used under the hood and there's no AOT-compatiblity, no?would suggest that.
Add System.Text.Json support for F# discriminated unions (dotnet#125610)
Add System.Text.Json support for F# discriminated unions (#125610)