asynkron / Wire

Binary serializer for POCO objects
Apache License 2.0
376 stars 63 forks source link

Serialize - DeSerialize between similar types. #139

Closed kunjee17 closed 7 years ago

kunjee17 commented 7 years ago

If we are passing data over the network, we are only having schema but not original types. With wire we are facing issues while serializing or deserializing between this kind of types. As Wire is some how storing the original value (namespace).

Here is simple example.

#I "../../packages/"
#r "Wire.0.8.2/lib/net45/Wire.dll"

open Wire
open System.IO

type User1 = {
    Name : string 
}

type User2 = {
    Name : string
}

let opt = SerializerOptions(preserveObjectReferences=false, surrogates = s)

let serializer = new Serializer(opt)
let p = 
    use stream = new MemoryStream()
    serializer.Serialize({User1.Name = "Kunjan"},stream)
    stream.ToArray()

let d1 = 
    use stream = new MemoryStream(p)
    serializer.Deserialize<User2>(stream)

printfn "%A" d1.Name

Here d1 is not working. While it will work with any JSON serializer. Is there any options I am missing?

Horusiath commented 7 years ago

@kunjee17 this is result of having polymorphic deserialization. This means that each serialized payload knows it's own type, so you don't have to provide it manually upon deserialization.

I.e. if you have an array new Animal[] { new Cat(name:"Sam"), new Dog(name:"Max") } you could deserialize it with serializer.Deserialize<object>(stream) and you'd still have valid types produced with no need to make casts between them. No JSON serializer would be able to do that without embedding type names in its content.

So this is deliberate decision, deeply set into the library itself.

kunjee17 commented 7 years ago

@Horusiath yeah. Seems like that. But what if I am trying to send data over the wire. It is having type details with it. But on other project, types are not exactly the same. (namespace is different to be precise ). Is there any way to do it in that case?

rogeralsing commented 7 years ago

@kunjee17 it's a matter of use the right tool for the right problem. Wire is as @Horusiath says, a polymorphic serializer, meaning it will encode type information in the payload.

While it could in theory be possible to have some form of type replacement support, that feels very much like the wrong way to go. Use a serializer that fits your needs, it's all about trade offs.

kunjee17 commented 7 years ago

Thanks @rogeralsing and @Horusiath for details explanation. I am closing the issue.