Skip to content

Instantly share code, notes, and snippets.

@wegry
Last active November 12, 2017 12:51
Show Gist options
  • Save wegry/18c1cd01dac070f9973288783f70ef93 to your computer and use it in GitHub Desktop.
Save wegry/18c1cd01dac070f9973288783f70ef93 to your computer and use it in GitHub Desktop.
F# Enum Style Discriminated Unions serialized to strings with Json.NET for DUs with empty cases
// Fsharp 4.1.0
open System
open Newtonsoft.Json // 10.0.3
open Newtonsoft.Json.Converters
type ToStringJsonConverter () =
inherit JsonConverter()
override this.CanConvert objectType = true;
override this.WriteJson (writer: JsonWriter, value: obj, serializer: JsonSerializer): unit =
writer.WriteValue(value.ToString())
override this.CanRead = false
override this.ReadJson (reader: JsonReader, objectType: Type, existingValue: obj, serializer: JsonSerializer) : obj =
raise (new NotImplementedException());
do
let settings = new JsonSerializerSettings()
settings.Converters.Add(new StringEnumConverter (CamelCaseText = true))
JsonConvert.DefaultSettings <- fun () -> settings
[<JsonConverter(typeof<ToStringJsonConverter>)>]
type HowLame =
| PrettyLame
| SuperLame
type LameScale =
| One = 1
| Ten = 10
type Lame = {
howLame: HowLame;
onAScaleOf: LameScale;
}
[<EntryPoint>]
let main argv =
let lame = { howLame = PrettyLame;
onAScaleOf = LameScale.Ten }
let ser = JsonConvert.SerializeObject(lame)
// {"soLame":{"Case":"PrettyLame"}} by default
printfn "%s" ser
0 // return an integer exit code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment