Created
April 25, 2016 19:16
-
-
Save imerchant/c2046fab9ab39d0a47fe827a9d299fde to your computer and use it in GitHub Desktop.
Json.NET Type Convertor for F# Option<_> support
This file contains 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
module OptionTypeConverter | |
open System | |
open Microsoft.FSharp.Reflection | |
open Newtonsoft.Json | |
// http://gorodinski.com/blog/2013/01/05/json-dot-net-type-converters-for-f-option-list-tuple/ | |
type OptionTypeConverter() = | |
inherit JsonConverter() | |
override x.CanConvert(t) = | |
t.IsGenericType && t.GetGenericTypeDefinition() = typedefof<option<_>> | |
override x.WriteJson(writer, value, serializer) = | |
let value = | |
if value = null then null | |
else | |
let _,fields = FSharpValue.GetUnionFields(value, value.GetType()) | |
fields.[0] | |
serializer.Serialize(writer, value) | |
override x.ReadJson(reader, t, existingValue, serializer) = | |
let innerType = t.GetGenericArguments().[0] | |
let innerType = | |
if innerType.IsValueType then (typedefof<Nullable<_>>).MakeGenericType([|innerType|]) | |
else innerType | |
let value = serializer.Deserialize(reader, innerType) | |
let cases = FSharpType.GetUnionCases(t) | |
if value = null then FSharpValue.MakeUnion(cases.[0], [||]) | |
else FSharpValue.MakeUnion(cases.[1], [|value|]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment