Tarmil / FSharp.SystemTextJson

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

Allow unionTagName to be part of the record type definition when deserializing union of records #100

Closed Zaid-Ajaj closed 2 years ago

Zaid-Ajaj commented 2 years ago

Description

Right now, when deserializing a union where each case is a record, it appears that we cannot have the discriminator property be part of the record definition itself. The library throws an exception saying that the field is missing from the JSON, even though it is indeed available.

Reproduction

open System.Text.Json
open System.Text.Json.Serialization

let options = JsonSerializerOptions ()
let encoding =
    JsonUnionEncoding.InternalTag
    ||| JsonUnionEncoding.UnwrapRecordCases
    ||| JsonUnionEncoding.UnwrapFieldlessTags
    ||| JsonUnionEncoding.UnwrapOption
    ||| JsonUnionEncoding.AdjacentTag

// using __typename as discriminator
let converter = JsonFSharpConverter(encoding, unionTagName="__typename")
options.Converters.Add(converter)

type Company = { name: string }

type Employee = {
    __typeName: string
    firstName: string
}

[<RequireQualifiedAccess>]
type SearchResult =
    | Company of company: Company
    | Employee of employee: Employee

let companyJson = "{ \"__typename\": \"Company\", \"name\": \"McCompany\" }"
let employeeJson = "{ \"__typename\": \"Employee\", \"firstName\": \"John\"  }"

// Works
let company = JsonSerializer.Deserialize<SearchResult>(companyJson, options)
printfn "%A" company

// Fails
let employee = JsonSerializer.Deserialize<SearchResult>(employeeJson, options)
printfn "%A" employee

Error

Unhandled exception. System.Text.Json.JsonException: Missing field for record type Program+Employee: __typeName
   at System.Text.Json.Serialization.JsonRecordConverter`1.ReadRestOfObject(Utf8JsonReader& reader, JsonSerializerOptions options, Boolean skipFirstRead)
   at System.Text.Json.Serialization.JsonRecordConverter`1.System.Text.Json.Serialization.IRecordConverter.ReadRestOfObject(Utf8JsonReader& reader, JsonSerializerOptions options, Boolean skipFirstRead)

Expected

To be able to deserialize employeeJson as SearchResult and populate __typename with "Employee"

Actual

An exception is thrown

Tarmil commented 2 years ago

I see, you want the "__typename" field to be used both as the tag for SearchResult and a field for Employee. It's not something I would have expected to be needed, but it's reasonable to expect it to work.

Zaid-Ajaj commented 2 years ago

It's not something I would have expected to be needed, but it's reasonable to expect it to work.

It is required sometimes when working with Snowflaqe and configuring the serializer to use System.Text.Json. Right now, my workaround is to not generate the __typename field for the records but this isn't ideal when __typename is the only field that needs to be generated which is sometimes the case.