Open marner2 opened 2 years ago
You probably need something like this integrated into an FSharp version of the JsonFormatter
(but for valueoption
s):
type OptionConverter() =
inherit JsonConverter()
override x.CanConvert(t) = t.IsGenericType && t.GetGenericTypeDefinition() = typedefof<option<_>>
override x.WriteJson(writer, outer, serializer) =
let inner =
if outer = null then
null
else
let _, fields = FSharpValue.GetUnionFields(outer, outer.GetType())
fields[0]
if outer <> null && inner = null then
writer.WriteStartObject()
writer.WritePropertyName("Case")
writer.WriteValue("None")
writer.WriteEndObject()
else
serializer.Converters.Remove(x) |> ignore
serializer.Serialize(writer, inner)
serializer.Converters.Add(x)
override x.ReadJson(reader, t, _existingValue, serializer) =
let innerType = t.GetGenericArguments().[0]
let innerType = if innerType.IsValueType then typedefof<Nullable<_>>.MakeGenericType [| innerType |] else innerType
serializer.Converters.Remove(x) |> ignore
let value = serializer.Deserialize(reader, innerType)
serializer.Converters.Add(x)
let cases = FSharpType.GetUnionCases(t)
FSharpValue.MakeUnion(cases[1], [| value |])
This happens when trying to use the
JsonFormatter
for types with anyoptional
fields.Simple proto file:
Simple test:
Result: