fsprojects / Fleece

Json mapper for F#
http://fsprojects.github.io/Fleece
Apache License 2.0
199 stars 31 forks source link

How to encode an enum-style discriminated union #144

Closed marklam closed 10 months ago

marklam commented 10 months ago

I found one way to do it, and it seems fine, so in the absence of a "Discussions" section, I'll note it here for anyone who comes looking:

type EnumThing =
    | A
    | B
    with
        static member get_Codec () =
            codec {
                (fun () -> A) <!> jreq "A" (function | A -> Some () | _ -> None)
                (fun () -> B) <!> jreq "B" (function | B -> Some () | _ -> None)
            }
            |> ofObjCodec