fsprojects / FSharp.Json

F# JSON Reflection based serialization library
Apache License 2.0
226 stars 26 forks source link

How to handle literal interface instances? #69

Open tymokvo opened 5 months ago

tymokvo commented 5 months ago

I frequently need to use the interface object expressions feature when referring to types that come from abstracted core libraries as properties in concrete types.

However, it seems that these types are not serializable in FSharp.Json. E.g.:

#r "nuget: FSharp.Json"

open FSharp.Json

type IThing =
    abstract member value: int

type Thing = { innerThing: IThing }

{
    innerThing =
        { new IThing with
            member _.value = 1
        }
}
|> Json.serialize

yields

FSharp.Json.JsonSerializationError: Unknown type: IThing
   at FSharp.Json.Core.serializeNonOption@104(JsonConfig config, Type t, JsonField jsonField, Object value)
   at FSharp.Json.Core.serializeUnwrapOption@158(JsonConfig config, Type t, JsonField jsonField, Object value)      
   at FSharp.Json.Core.serializeProperty@180-1.Invoke(PropertyInfo prop)
   at FSharp.Json.Core.serializeRecord@216(JsonConfig config, Type t, Object therec)
   at FSharp.Json.Json.serializeEx(JsonConfig config, Object theobj)
   at <StartupCode$FSI_0002>.$FSI_0002.main@() in C:\a.fsx:line 10 
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)

Is there a way to configure this behavior? Either pass in a serializing function or simply mark these fields to be skipped?