Created
October 16, 2021 20:37
-
-
Save chgeuer/ef167b24d1c6226a04584649c25a5e72 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#r "nuget: Thoth.Json.Net, 7.1.0" | |
open Thoth.Json.Net | |
type Foo = | |
{ Name: string | |
Age: int } | |
module Encoders = | |
let fooDecoder : Decoder<Foo> = | |
Decode.object (fun fields -> { | |
Name = fields.Required.At [ "n" ] Decode.string | |
Age = fields.Required.At [ "a" ] Decode.int | |
}) | |
let fooEncoder (foo: Foo) = | |
Encode.object | |
[ ("n", Encode.string foo.Name) | |
("a", Encode.int foo.Age) | |
] | |
type Bar = | |
{ Name: string | |
FooThingie: Foo } | |
static member Decoder : Decoder<Bar> = | |
Decode.object (fun fields -> { | |
Name = fields.Required.At [ "n" ] Decode.string | |
FooThingie = fields.Required.At [ "f" ] Encoders.fooDecoder | |
}) | |
static member Encoder (bar: Bar) = | |
Encode.object | |
[ ("n", Encode.string bar.Name) | |
("f", Encoders.fooEncoder bar.FooThingie) ] | |
let enrich x = | |
x | |
|> Extra.withCustom Encoders.fooEncoder Encoders.fooDecoder | |
|> Extra.withCustom Bar.Encoder Bar.Decoder | |
[<EntryPoint>] | |
let main argv = | |
let myExtraCoders = | |
Extra.empty | |
|> enrich | |
let f = { Name = "bar"; FooThingie = { Name = "Christian"; Age = 49 } } | |
let json = Encode.Auto.toString (1, f, extra = myExtraCoders) | |
let f2 = Decode.Auto.fromString<Bar>(json, extra = myExtraCoders) | |
printfn "%s" json | |
printfn "%A" f2 | |
1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment