Tarmil / FSharp.SystemTextJson

System.Text.Json extensions for F# types
MIT License
329 stars 43 forks source link

NotSupported exception when dictionary key is union (DU) #177

Open pintset opened 10 months ago

pintset commented 10 months ago

Hi!

I would like to achieve the following serialization result for maps, when key is DU (case sensitivity for keys does not matter).

{
  "key-values": {
    "Key1": {
      "string-value": "A",
      "int-value": 1
    },
    "Key2": {
      "string-value": "B",
      "int-value": 2
    },
    "Key3": {
      "string-value": "C",
      "int-value": 3
    }
  }
}

In order to do that, I set MapFormat to MapFormat.Object, though it is not enough because I receive System.NotSupportedException: The type 'Program+SampleKey' is not a supported dictionary key using converter of type 'System.Text.Json.Serialization.JsonUnionConverter1[Program+SampleKey]'.

So I need to add a custom converter for the type on top of standard options. The question is, is it possible to configure options in the way so additional json converters are not required? Or maybe it is possible to improve the library in that way. Because it look like it does not support WriteAsPropertyName/ReadAsPropertyName as required.

Here is the sample code:

type SampleKey =
    | Key1
    | Key2
    | Key3

type SampleValue =
    { StringValue: string
      IntValue: int }

type SampleMap =
    { KeyValues: Map<SampleKey, SampleValue> }

type SampleKeyConverter() =
    inherit JsonConverter<SampleKey>()

    let read (reader: Utf8JsonReader) =
        let value = reader.GetString().ToLowerInvariant()
        match value with
        | "key1" -> Key1
        | "key2" -> Key2
        | "key3" -> Key3
        | _ -> failwith "Not supported"

    override _.Write(writer: Utf8JsonWriter, value: SampleKey, options: JsonSerializerOptions) =        
        value.ToString() |> writer.WriteStringValue

    override _.Read(reader: byref<Utf8JsonReader>, typeToConvert: System.Type, options: JsonSerializerOptions) =
        read reader

    override _.WriteAsPropertyName(writer: Utf8JsonWriter, value: SampleKey, options: JsonSerializerOptions) =
        value.ToString () |> writer.WritePropertyName

    override _.ReadAsPropertyName(reader: byref<Utf8JsonReader>, typeToConvert: System.Type, options: JsonSerializerOptions) =
        read reader

let jsonOptions =       
    let options =
        JsonFSharpOptions.FSharpLuLike()            
            .WithUnionTagCaseInsensitive()
            .WithMapFormat(MapFormat.Object)
            .ToJsonSerializerOptions()
    options.Converters.Insert(0, SampleKeyConverter())
    options.PropertyNamingPolicy <- JsonNamingPolicy.KebabCaseLower
    options

let keyValues =
    [ Key1, { StringValue = "A"; IntValue = 1 }
      Key2, { StringValue = "B"; IntValue = 2 }
      Key3, { StringValue = "C"; IntValue = 3 } ]
    |> Map.ofList

let testMap = { KeyValues = keyValues }

let jsonString = JsonSerializer.Serialize(testMap, jsonOptions)
printfn "%s" jsonString

let testMapBack =JsonSerializer.Deserialize<SampleMap>(jsonString, jsonOptions)
let test = testMap = testMapBack