Skip to content

STJ: NotSupportedException for JsonSerializer.Serialize<Object> on DU #128

Closed

Description

@rynoV

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 0

This 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 Test2 above), the serialization succeeds
  • If the value is not cast to obj (i.e. remove :>obj above), the serialization succeeds
  • If Options.Create(autoUnionToJsonObject = true) is passed to Serialize, the serialization succeeds even with the cast to obj

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

  1. rynoV commented on Apr 11, 2025

    @rynoV
    Author

    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:

    type Test =
        | Test1 of int
        | Test2 of int
    
    type TC<'T>() =
        inherit UnionConverter<'T>()
    
        override x.CanConvert t = 
            (t = typeof<'T> || t.DeclaringType = typeof<'T>) && FsCodec.Union.isUnion t
    
    let s v =
        let opt = Options.Create(converters = [|TC<Test>()|])
        System.Text.Json.JsonSerializer.Serialize(v:>obj, opt)
    
    do s <| Test1 0

    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.

  2. rynoV commented on Apr 11, 2025

    @rynoV
    Author

    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)

  3. bartelink commented on Apr 13, 2025

    @bartelink
    Contributor

    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

  4. rynoV commented on Apr 14, 2025

    @rynoV
    Author

    Your second comment suggests that altering the UnionConverter CanConvert impl could be a viable fix?

    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.

  5. bartelink commented on Apr 14, 2025

    @bartelink
    Contributor

    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. Test
    • for a specific case (e.g. Test1), 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 Test with [<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.

  6. rynoV commented on Apr 14, 2025

    @rynoV
    Author

    I suspect that if the converter predicate is correct, then STJ will pick it up (assuming you tag type Test with [<JsonConverter(typeof<UnionConverter>)>] ?

    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 UnionConverter subclass TC from above, but use it as an attribute on Test instead of registering it in the options object, I get the original error.

    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.

    Unless I'm mistaken about the above, I think this would be best. Appreciate your time

  7. bartelink commented on Apr 14, 2025

    @bartelink
    Contributor

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

  8. njlr commented on Feb 16, 2026

    @njlr

    Edit: different issue, but will leave the below in case useful.


    Work-around using FSharp.SystemTextJson?

    #r "nuget: FsCodec, 3.1.0"
    #r "nuget: FsCodec.SystemTextJson, 3.1.0"
    #r "nuget: FSharp.SystemTextJson, 1.4.36"
    
    open System
    open FsCodec
    open System.Text.Json
    open System.Text.Json.Serialization
    
    type Direction =
      | Up
      | Down
    
    type Moved =
      {
        Direction : Direction
        Amount : int
      }
    
    type Event =
      | Moved of Moved
      interface TypeShape.UnionContract.IUnionContract
    
    let codec : IEventCodec<Event, ReadOnlyMemory<byte>, unit> =
      // Configure using FSharp.SystemTextJson
      let options =
        JsonFSharpOptions.Default()
          .ToJsonSerializerOptions()
      options.PropertyNamingPolicy <- JsonNamingPolicy.CamelCase
      FsCodec.SystemTextJson.Codec.Create(options)
    
    let event =
      Moved
        {
          Direction = Up
          Amount = 10
        }
    
    let encoded = codec.Encode((), event)
    
    printfn $"hex = %s{Convert.ToHexStringLower(encoded.Data.Span)}"

    hex = 7b22646972656374696f6e223a7b2243617365223a225570227d2c22616d6f756e74223a31307d

  9. bartelink commented on Feb 17, 2026

    @bartelink
    Contributor

    @njlr I don't see where you're boxing the event - the OP pertains to a specific problem if you end up running a Serialize<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 your Direction above ?

  10. njlr commented on Feb 17, 2026

    @njlr

    @njlr I don't see where you're boxing the event - the OP pertains to a specific problem if you end up running a Serialize<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 your Direction above ?

    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!

  11. bartelink commented on Feb 17, 2026

    @bartelink
    Contributor

    @njlr Note in general for event encoding, I'd avoid taking the FSharp.SystemTextJson dependency 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:

    let codec : IEventCodec<Event, ReadOnlyMemory<byte>, unit> =
      // TOCONSIDER add `autoUnionToJsonObject = true)` to also opt into converting unions with bodies to internal tag rendering
      let options = Options.Create(camelCase = true, autoTypeSafeEnumToJsonString = true)
      FsCodec.SystemTextJson.Codec.Create(options)

    (For web layers, its more debatable, but even there, raw STJ with FsCodec UnionEncoder here and there can go a long way)

  12. bartelink commented on Mar 26, 2026

    @bartelink
    Contributor

    @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

  13. added a commit that references this issue on Mar 26, 2026
    5d93249
  14. changed the title [-][`System.Text.Json`] `NotSupportedException` when passing `obj` to `JsonSerializer.Serialize`[/-] [+]STJ: NotSupportedException for JsonSerializer.Serialize<Object> on DU[/+] on Mar 26, 2026
  15. bartelink commented on Mar 26, 2026

    @bartelink
    Contributor

    @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 as Object" - I guess the answer is probably that this is excluded by Design

    NOTE wanting/needing to use Serialize<Object> is a design smell - things Just Work if you Serialize<UnionType>(instance). Similarly having an object in any type tree is also not a good thing. There are various workarounds (registering a custom converter whose CanConvert returns true for typeof<Object> that forwards the call to Serialize(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?

  16. bartelink commented on Mar 27, 2026

    @bartelink
    Contributor

    @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> and Union.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

  17. rynoV commented on Mar 27, 2026

    @rynoV
    Author

    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

  18. rynoV commented on Mar 27, 2026

    @rynoV
    Author

    Funnily enough, dotnet/runtime#125610 was just merged, so that probably fixes my use case

  19. bartelink commented on Mar 27, 2026

    @bartelink
    Contributor

    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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions