Skip to content

Instantly share code, notes, and snippets.

@alfonsogarciacaro
Created January 25, 2019 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alfonsogarciacaro/11e0aa8acc87cbbca8948e2cdfae15b4 to your computer and use it in GitHub Desktop.
Save alfonsogarciacaro/11e0aa8acc87cbbca8948e2cdfae15b4 to your computer and use it in GitHub Desktop.
Extra Thoth.Json coders for enum types
open Thoth.Json.Net
type MyEnum =
| Foo = 1
| Bar = 2
type MyRecord =
{ Field1: string
Field2: MyEnum }
let inline enumDecoder< ^T when ^T : enum<int32> > =
Decode.int |> Decode.map (fun x -> enum< ^T > x)
let test() =
let extra =
Extra.empty
|> Extra.withCustom (fun (x: MyEnum) -> int x |> Encode.int) enumDecoder
let enc = Encode.Auto.generateEncoder<MyRecord>(extra=extra)
let dec = Decode.Auto.generateDecoder<MyRecord>(extra=extra)
let x = { Field1 = "Hello World from F#!"; Field2 = MyEnum.Bar }
let json = enc x |> Encode.toString 4
let parsed = Decode.fromString dec json
printfn "JSON %s" json
printfn "PARSED %A" parsed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment