Skip to content

Conversation

@Tarmil
Copy link
Owner

@Tarmil Tarmil commented Jun 9, 2025

Fixes #181.

Add member WithOverrideMembers taking IDictionary<string, seq<Attribute>> to JsonFSharpOptions.

Example uses:

  • Override attributes on record fields:

    type MyRecord = { x: int }
    
    let options =
        JsonFSharpOptions.Default()
            .WithOverrides(fun o -> dict [
                typeof<MyRecord>, o.WithOverrideMembers(dict [
                    "x", [JsonNameAttribute "y"]
                ])
            ])
            .ToJsonSerializerOptions()
    
    JsonSerializer.Serialize({ x = 1 }, o)
    // --> {"y":1}
  • Override attributes on union cases:

    let options =
        JsonFSharpOptions.Default()
            .WithOverrides(fun o -> dict [
                typedefof<Result<_, _>>, o
                    .WithUnionInternalTag()
                    .WithUnionNamedFields()
                    .WithUnionTagName("isSuccess")
                    .WithOverrideMembers(dict [
                        nameof Ok, [
                            JsonNameAttribute true
                            JsonNameAttribute("value", Field = "ResultValue")
                        ]
                        nameof 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 merged commit d36bbaf into master Jun 9, 2025
6 checks passed
@Tarmil Tarmil deleted the override-members branch June 9, 2025 14:55
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

Successfully merging this pull request may close these issues.

Allow overriding property and union case attributes in options

2 participants