FsPickler icon indicating copy to clipboard operation
FsPickler copied to clipboard

unpickling objects to an identical structure with a different qualified name

Open thomasd3 opened this issue 4 years ago • 1 comments

I've had some trouble with this. In the past I opened a ticket (https://github.com/mbraceproject/FsPickler/issues/124) for which the suggestion was to make a custom ITypeNameConverter.

I then opened a question on StackExchange and an answer proposed a good solution. I would suggest to add an edit to the doc giving the answer as an example since it's not that straightfoward to see how all the pieces fit together, unless you're familiar with the pipeline.

Here is the link to the question and its answer: https://stackoverflow.com/questions/70369176/binary-deserialization-to-another-type-with-fspickler/70373421#70373421

thomasd3 avatar Dec 17 '21 18:12 thomasd3

This problem happens between FSI sessions too.

#r "nuget: FsPickler"
open MBrace.FsPickler


type Foo = {bar:string}


let writer: System.IO.TextWriter = null // dummy
let reader: System.IO.TextReader = null // dummy

let xmlizer = FsPickler.CreateXmlSerializer()
xmlizer.Serialize(writer,  {bar=""} )

/// this fails if not called in the same Fsi session 
let foo = xmlizer.Deserialize<Foo>(reader)

Because types get a FSI session prefix:

Image

to fix it a converter can be used:

/// needed to fix types that include an incrementing FSI_0001 prefix.
let converter = { 
    new ITypeNameConverter with
        member this.OfSerializedType t = // used for Serializer and Deserializer
            if t.Name.StartsWith "FSI_00" then
                { t with Name = t.Name.Substring(1 + t.Name.IndexOf '+') }  
            else  
                t
        member this.ToDeserializedType t =  t 
    } 


let saveXmlizer = FsPickler.CreateXmlSerializer(typeConverter = converter)
saveXmlizer.Serialize(writer,  {bar=""} )


/// this does NOT fail if called in another fsi session 
let foo2 = saveXmlizer.Deserialize<Foo>(reader)

@eiriktsarpalis would you accept a PR to add this to the docs? Since FSI is a common use-case. Or even build it in by default? Or is there a better workaround?

goswinr avatar Sep 23 '25 12:09 goswinr