Tarmil / FSharp.SystemTextJson

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

Null strings throw #107

Closed ImaginaryDevelopment closed 2 years ago

ImaginaryDevelopment commented 2 years ago

Simple record with a null string throws.

open System.Text.Json
type Test = {
    ProjectId: string
    Foo: int
}

let value = { ProjectId = null; Foo = 1}

module Serializer =
    let serializerOpts =
        let so = System.Text.Json.JsonSerializerOptions(
                    WriteIndented = true
        )
        so.Converters.Add(Serialization.JsonFSharpConverter()) // without this line it works fine

        so
    let serialize<'t> (x:'t) = JsonSerializer.Serialize(x,serializerOpts)
    let deserialize<'t> (x: string) : 't =
        JsonSerializer.Deserialize(x, serializerOpts)

()       

value
|> Serializer.serialize
|> Serializer.deserialize<Test>
|> ignore

JsonException: Test.ProjectId was expected to be of type String, but was null.

Tarmil commented 2 years ago

If this is something you need then you can use JsonFSharpConverter(allowNullFields = true).

ImaginaryDevelopment commented 2 years ago

If this is truly intended behavior, simple nullable types throwing, then I guess this issue can be closed. I did not expect this to be by design.

kentcb commented 2 years ago

Was also bitten by this today, but in the context of a DU:

type SomeUnion =
| Something of string

What's weird is that I can successfully serialize null |> SomeUnion.Something just fine, but deserializing it fails with the stated error message.

For me, allowNullFields = true hasn't helped (perhaps due to being a DU?)

Tarmil commented 2 years ago

@kentcb If this also fails with allowNullFields = true, then I think your issue is actually closer to #106.

ImaginaryDevelopment commented 2 years ago

I don't think null strings should throw at all anywhere