Created
May 12, 2023 06:36
-
-
Save suside/8e9172879051ac897e5c17d6edf596b6 to your computer and use it in GitHub Desktop.
Union serialization provider for F#
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
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