Oxpecker icon indicating copy to clipboard operation
Oxpecker copied to clipboard

Add `ctx.BindJson<'T>(jsonSerializerOptions)`

Open pkese opened this issue 1 year ago • 3 comments

It would be nice if context.BindJson would allow passing custom JsonSerializerOptions.

pkese avatar Dec 03 '24 22:12 pkese

@pkese have you seen the json custom configuration docs https://lanayx.github.io/Oxpecker/src/Oxpecker/#writing-json ?

services.AddSingleton<IJsonSerializer>(
        SystemTextJsonSerializer(specificOptions)) |> ignore

Lanayx avatar Dec 03 '24 22:12 Lanayx

Yes, I have, but I have different parts of APIs that are expecting different types of data:
one part of my API is public, the other part is exposed to F# client sending Thoth.Json compliant data, so I need two sets of JsonSerializerOptions

pkese avatar Dec 03 '24 22:12 pkese

I see. I think that current helpers like BindJson are just for the most common scenarios, but it should be very easy to add customize, for example

module My =
    let anotherSerializer = SystemTextJsonSerializer(myOptions)

and then

[<Extension>]
static member WriteJson2<'T>(ctx: HttpContext, value: 'T) =
    My.anotherSerializer.Serialize(value, ctx, false)

or

[<Extension>]
static member BindJson2<'T>(ctx: HttpContext) =
    task {
        try
            return! My.anotherSerializer.Deserialize<'T>(ctx)
        with ex ->
            return raise <| ModelBindException("Unable to deserialize model from JSON", ex)
    }

so given this is easy achievable I'm reluctant to extend API for this case

Lanayx avatar Dec 03 '24 23:12 Lanayx