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

Allow overriding property and union case attributes in options #181

Open
Tarmil opened this issue Feb 12, 2024 · 0 comments
Open

Allow overriding property and union case attributes in options #181

Tarmil opened this issue Feb 12, 2024 · 0 comments
Labels
enhancement New feature or request

Comments

@Tarmil
Copy link
Owner

Tarmil commented Feb 12, 2024

Allow specifying which attributes should apply to a given property or union case in the options. This is useful to override the format of a type that is not under the developer's control, or simply to keep DTOs lean.

Example:

type MyRecord = { x: int }

let options =
    JsonFSharpOptions()
        .WithOverrides(fun o -> dict [
            typeof<MyRecord>, o.WithOverrideProperty("x", [JsonNameAttribute "y"])
        ])
        .ToJsonSerializerOptions()

JsonSerializer.Serialize({ x = 1 }, o)
// --> {"y":1}

Example combined with #180 to fully control the format of the standard library's Result<'ok, 'error>:

let options =
    JsonFSharpOptions()
        .WithOverrides(fun o -> dict [
            typedefof<Result<_, _>>, o
                .WithUnionInternalTag()
                .WithUnionNamedFields()
                .WithUnionTagName("isSuccess")
                .WithOverrideCase("Ok", [
                    JsonNameAttribute true
                    JsonNameAttribute("value", Field = "ResultValue")
                ])
                .WithOverrideCase("Error", [
                    JsonNameAttribute false
                    JsonNameAttribute("error", Field = "ErrorValue")
                ])
        ])

JsonSerializer.Serialize(Ok 42, options)
// --> {"isSuccess":true,"value":42}

JsonSerializer.Serialize(Error "Internal error", options)
// --> {"isSuccess":false,"error":"Internal error"}
@Tarmil Tarmil added the enhancement New feature or request label Feb 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant