Repository navigation
Description
Dotnet version: 9.0.3
STJ: 9.0.4
FsCodec: 3.0.3
There's a strange edge case when passing an obj to JsonSerializer.Serialize:
open System.Text.Json.Serialization
open FsCodec.SystemTextJson
let s v =
System.Text.Json.JsonSerializer.Serialize(v:>obj)
[<JsonConverter(typeof<UnionConverter<Test>>)>]
type Test =
| Test1 of int
| Test2 of int
do s <| Test1 0This will fail with:
System.NotSupportedException: F# discriminated union serialization is not supported. Consider authoring a custom converter for the type. The unsupported member type is located on type 'Test+Test1'. Path: $.
---> System.NotSupportedException: F# discriminated union serialization is not supported. Consider authoring a custom converter for the type.
at System.Text.Json.Serialization.Converters.UnsupportedTypeConverter`1.Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
--- End of inner exception stack trace ---
at System.Text.Json.ThrowHelper.ThrowNotSupportedException(WriteStack& state, Exception innerException)
at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1.Serialize(Utf8JsonWriter writer, T& rootValue, Object rootValueBoxed)
at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1.SerializeAsObject(Utf8JsonWriter writer, Object rootValue)
at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1.Serialize(Utf8JsonWriter writer, T& rootValue, Object rootValueBoxed)
at System.Text.Json.JsonSerializer.WriteString[TValue](TValue& value, JsonTypeInfo`1 jsonTypeInfo)
at System.Text.Json.JsonSerializer.Serialize[TValue](TValue value, JsonSerializerOptions options)
I call it an edge case because there are a couple ways where this doesn't fail:
- If the union is changed to have a single case (e.g. remove
Test2above), the serialization succeeds - If the value is not cast to
obj(i.e. remove:>objabove), the serialization succeeds - If
Options.Create(autoUnionToJsonObject = true)is passed toSerialize, the serialization succeeds even with the cast toobj
Something interesting is the error message refers to the union case of the value being serialized (Test.Test1), whereas the normal NotSupportedException will refer only to the type (Test), I believe because somewhere along the line Object.GetType() is being called on the value.
When I override UnionConverter and print when methods are called, it shows that CanConvert is called once and returns true, but the exception is thrown before Write is called.
This case comes up when using SignalR: https://github.com/dotnet/aspnetcore/blob/c946659badd12f1a632bce7d7309b3dc4dc1275f/src/SignalR/common/Protocols.Json/src/Protocol/JsonHubProtocol.cs#L917
Activity
rynoV commentedon Apr 11, 2025
It seem like STJ is initially using the right converter, but then at some point uses the type of the value which is the individual union case, so it doesn't find the JsonConverter attribute, and fails with not supported.
If I do the following I can make it work:
With the important pieces being to register the converter in the options because the attribute lookup fails, and for the converter to accept when the DeclaringType is equal as well.
rynoV commentedon Apr 11, 2025
This seems like it won't be possible to fix in FsCodec alone so I brought the issue up in STJ as well: dotnet/runtime#55744 (comment)
bartelink commentedon Apr 13, 2025
Your second comment suggests that altering the UnionConverter CanConvert impl could be a viable fix?
If you make a PR with a fix and a test, I can push an alpha for you to validate
Having said that, I suspect that there's something deeper that can/should be done as I suspect ASP.NET with STJ will also produce the same problem as dotnet/fsharp#17864
However, not being deeply familiar with the end to end details, I'd prefer to know that it cant be solved at ASP.NET or STJ level before we add the wart here...
I note FSharp.SystemTextJson also does not have an equivalent check
rynoV commentedon Apr 14, 2025
It would be possible to fix the case where the converter is registered in the JsonSerializerOptions, but if it is used as an annotation it would still go unfound.
I'm also not very happy with the fix I described because it's relying on internal details of F#.
I do think this should be fixed in STJ because it's using the internal F# generated type to decide on the converter to use. If STJ gets changed to use the top-level DU type instead (dotnet/runtime#55744 (comment)) then no change should be required to fscodec.
For now my plan is to use the workaround I outlined and monitor that issue in STJ.
bartelink commentedon Apr 14, 2025
OK, but in your workaround you have
|| t.DeclaringType = typeof<'T>, which should make the predicate pass for a boxed instance:typeof<'T>is the union type, i.e.TestTest1), the generated type logic is a nested type within the base/generic/abstract union type (i.e.Test)This is the key difference between using raw STJ and STJ with options with
autoUnionToJsonObject = true(i.e. it has the broader check that also checks the DeclaringType)I suspect that if the converter predicate is correct, then STJ will pick it up (assuming you tag
type Testwith[<JsonConverter(typeof<UnionConverter<Test>>)>]?But I could definitely be wrong (and if I am, your point that it requires something to happen within STJ is upheld).
If you're happy, I'm happy, and this issue can document the workaround until we have a definitive yes/no as to whether there is something that can/should be done at the STJ level.
rynoV commentedon Apr 14, 2025
My assumption of the issue is that when the converter is registered as an attribute, that converter only gets found when STJ is looking at the exact type annotated with that attribute, which isn't the case when the union instance gets boxed to
obj, because the reflection used in STJ returns the unannotated generated internal subclass.I haven't confirmed this by looking at the STJ code, but it makes sense given that if I use that same workaround
UnionConvertersubclassTCfrom above, but use it as an attribute onTestinstead of registering it in the options object, I get the original error.Unless I'm mistaken about the above, I think this would be best. Appreciate your time
bartelink commentedon Apr 14, 2025
Good point; your analysis makes sense to me, though I can't say I've analyzed deeply on the STJ side of things; hopefully Eirik will get to it in due course...
njlr commentedon Feb 16, 2026
Edit: different issue, but will leave the below in case useful.
Work-around using FSharp.SystemTextJson?
bartelink commentedon Feb 17, 2026
@njlr I don't see where you're
boxing the event - the OP pertains to a specific problem if you end up running aSerialize<Object>(someDU); not just a simple case of a DU without a converter attribute occurring in the tree?Note also if you use FsCodec config with
(autoTypeSafeEnumToJsonString = true), then it should implicitly handle yourDirectionabove ?njlr commentedon Feb 17, 2026
Ah my mistake.
I had a similar error myself, searched for it and found a ticket, lost the tab, found a fix (above worked for me), then lost the original issue I had open.
This was the one I found trying to find it again but clearly the wrong one!
bartelink commentedon Feb 17, 2026
@njlr Note in general for event encoding, I'd avoid taking the
FSharp.SystemTextJsondependency until there's a proper reason - you're opting into way less custom logic and conversions and can just troubleshoot based on things being STJ without having to consider FSSTJ.In particular, your above config can be replicated by:
(For web layers, its more debatable, but even there, raw STJ with FsCodec UnionEncoder here and there can go a long way)
bartelink commentedon Mar 26, 2026
@rynoV I'm considering closing this as I don't want to leave an open issue for an extended period where the finger of blame might benefit from being pointed elsewhere.
This discussion might be useful in terms of understanding the variations of possible type hierarchy used under the hood to represent the DU depending on the number of cases: fsharp/fslang-suggestions#1463
I'll have a quick check if I can repro and understand based on the above first independently, but for now I'll give @copilot a run at it and close unless it can triage such that we end up with a clearer repro that points at a universal solution via changing only the implementation of UnionConverter
Fix UnionConverter.CanConvert to handle DU case nested types for boxe…
[-][`System.Text.Json`] `NotSupportedException` when passing `obj` to `JsonSerializer.Serialize`[/-][+]STJ: NotSupportedException for JsonSerializer.Serialize<Object> on DU[/+]bartelink commentedon Mar 26, 2026
@rynoV The PR has corrected the CanConvert so it works if registered and/or if the STJ ever picks up the converter based on the base Type of the DU instance in the Serialize scenario
I added a note in dotnet/aspnetcore#51481 (comment)
Thanks for all the digging, engagement and the clean repro that ultimately led to this
Next up I/we need to research whether STJ provides any clean way to pick up converter tags from "DU case asObject" - I guess the answer is probably that this is excluded by DesignNOTE wanting/needing to use
Serialize<Object>is a design smell - things Just Work if youSerialize<UnionType>(instance). Similarly having anobjectin any type tree is also not a good thing. There are various workarounds (registering a custom converter whoseCanConvertreturnstruefortypeof<Object>that forwards the call toSerialize(instance, instance.GetType())(that overload does a converter attribute check including the base type)Will be releasing a 3.1.1 pretty soon incorporating this.
@rynoV In your consumption pattern, can you avoid doing this? Do you actually unavoidably have an
obj[]in play?bartelink commentedon Mar 27, 2026
@rynoV Strongly considering merging #144 to address my reflection in #143
It may even make sense to generalize the Factory logic to say 'if
t = typeof<obj>andUnion.isUnion(instance.GetType().DeclaringType)such that a single factory redirects all F# unions to a UnionConverter for them.Or perhaps STJ can provide such a construct in the box at some point?
It all comes back to the root question though - what is your actual use case here. If we had that context it may be the case that there's a better overall solution without any of these gymnastics
rynoV commentedon Mar 27, 2026
Hi @bartelink , thank you for looking into this more. Agreed with merging #144, the CanConvert override was more of a hack to show what was going on and I didn't really give it much thought nor do I use that code.
The use case here was in using SignalR, which unavoidably boxed the values. I think it's fine to close this issue with #144 documenting the workaround
rynoV commentedon Mar 27, 2026
Funnily enough, dotnet/runtime#125610 was just merged, so that probably fixes my use case
bartelink commentedon Mar 27, 2026
Yes, amusing timing -just saw it in notifications; had been unaware it was even in flight, which is a nice surprise (though I guess C# unions brought it all to the fore)