@@ -36,6 +36,7 @@ The serialization and deserialization of `FSharp.SystemTextJson` can be customiz
3636- [ Attributes] ( #attributes )
3737 - [ JsonFSharpConverter] ( #jsonfsharpconverter )
3838 - [ JsonName] ( #jsonname )
39+ - [ Attribute overrides] ( #attribute-overrides )
3940
4041<!-- END doctoc generated TOC please keep comment here to allow auto update -->
4142
@@ -996,3 +997,56 @@ However, it also includes its own attribute `JsonNameAttribute` which provides m
996997 JsonSerializer.Serialize(Error "Failed to retrieve x", options)
997998 // --> {"isSuccess":false,"error":"Failed to retrieve x"}
998999 ```
1000+
1001+ ### Attribute overrides
1002+
1003+ In order to customize the names of record fields and union cases and fields for a type that you can't or don't want to enrich with attributes,
1004+ the alternate solution is to use the `OverrideMembers` option.
1005+
1006+ * Override attributes on record fields:
1007+
1008+ ```fsharp
1009+ type MyRecord = { x: int }
1010+
1011+ let options =
1012+ JsonFSharpOptions.Default()
1013+ .WithOverrides(fun o -> dict [
1014+ typeof<MyRecord>, o
1015+ .WithOverrideMembers(dict [
1016+ "x", [JsonNameAttribute "y"]
1017+ ])
1018+ ])
1019+ .ToJsonSerializerOptions()
1020+
1021+ JsonSerializer.Serialize({ x = 1 }, o)
1022+ // --> {"y":1}
1023+ ```
1024+
1025+ * Override attributes on union cases:
1026+
1027+ ```fsharp
1028+ let options =
1029+ JsonFSharpOptions.Default()
1030+ .WithOverrides(fun o -> dict [
1031+ typedefof<Result<_, _>>, o
1032+ .WithUnionInternalTag()
1033+ .WithUnionNamedFields()
1034+ .WithUnionTagName("isSuccess")
1035+ .WithOverrideMembers(dict [
1036+ nameof Ok, [
1037+ JsonNameAttribute true
1038+ JsonNameAttribute("value", Field = "ResultValue")
1039+ ]
1040+ nameof Error, [
1041+ JsonNameAttribute false
1042+ JsonNameAttribute("error", Field = "ErrorValue")
1043+ ]
1044+ ])
1045+ ])
1046+
1047+ JsonSerializer.Serialize(Ok 42, options)
1048+ // --> {"isSuccess":true,"value":42}
1049+
1050+ JsonSerializer.Serialize(Error "Internal error", options)
1051+ // --> {"isSuccess":false,"error":"Internal error"}
1052+ ```
0 commit comments