Skip to content

Instantly share code, notes, and snippets.

@suside
Created May 12, 2023 06:36
Show Gist options
  • Save suside/8e9172879051ac897e5c17d6edf596b6 to your computer and use it in GitHub Desktop.
Save suside/8e9172879051ac897e5c17d6edf596b6 to your computer and use it in GitHub Desktop.
Union serialization provider for F#
let UnionToString (u: 'a) =
match FSharpValue.GetUnionFields(u, typeof<'a>) with
| case, _ -> case.Name
let StringToUnion<'a> (s: string) =
match FSharpType.GetUnionCases typeof<'a> |> Array.filter (fun case -> case.Name = s) with
| [| case |] -> FSharpValue.MakeUnion(case, [||]) :?> 'a
| _ -> failwithf "Unable to parse %A" s
type UnionStringSerializer<'a>() =
inherit SerializerBase<'a>()
override this.Deserialize(context, args) =
match context.Reader.GetCurrentBsonType() with
| BsonType.String -> context.Reader.ReadString() |> StringToUnion
| other -> failwithf "Unable to parse %A" other
override this.Serialize(context, args, value: 'a) =
context.Writer.WriteString <| UnionToString value
BsonSerializer.RegisterSerializer(UnionStringSerializer<MyType>())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment