Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom serializer/JsonConverter for a record #185

Open
rynoV opened this issue Apr 25, 2024 · 2 comments
Open

Custom serializer/JsonConverter for a record #185

rynoV opened this issue Apr 25, 2024 · 2 comments

Comments

@rynoV
Copy link

rynoV commented Apr 25, 2024

Thanks for making this!

I didn't see this in the docs so I thought I'd mention it here: when registering a custom JsonConverter for a type in JsonFSharpTypes (e.g. records), it seems necessary to add it to the JsonSerializerOptions.Converters list before adding the json fsharp serializer options with AddToJsonSerializerOptions. Otherwise the fsharp record converter takes precedence.

Adding the JsonConverter directly to the record doesn't seem to take precedence. And it doesn't seem like using ToJsonSerializerOptions would work either.

@nkosi23
Copy link

nkosi23 commented Jun 28, 2024

Thanks, this has been very helpful to me.

@draganjovanovic1
Copy link

Hi @rynoV I am using custom JsonConverter attributes on some of my record and union types but serializer won't use them if I include JsonFSharpOptions in my JsonSerializerOptions.

I can't register all custom converters here in JsonSerializerOptions as I can't reference them and I don't like idea of adding them all in one place even if I could.

Any suggestion what to try? Thanks.

My options:

let options = JsonSerializerOptions ()
options.PropertyNamingPolicy <- JsonNamingPolicy.CamelCase
options.WriteIndented <- true
options.IndentSize <- 4
options.DefaultIgnoreCondition <- JsonIgnoreCondition.WhenWritingNull
options.NumberHandling <- JsonNumberHandling.AllowReadingFromString
options.Encoder <- JavaScriptEncoder.Default
options.Converters.Add (DateTimeConverterJsonConverter ())
options.Converters.Add (DateTimeOffsetConverterJsonConverter ())
options.Converters.Add (GuidJsonConverter ())
// with this part, my custom converter don't work, without it all good
let fsharpOptions =
    JsonFSharpOptions
        .Default()
        .WithIncludeRecordProperties()
        .WithUnionNamedFields()
        .WithSkippableOptionFields()
fsharpOptions.AddToJsonSerializerOptions (options)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants