(De)Serializing interfaces

Rikki Cattermole via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 22 20:09:01 PDT 2015


On 8/23/2015 7:14 AM, nims wrote:
> I think interfaces are very powerful and I heavily use them. The only
> problem I have with them is that serializing/deserializing them to XML
> or JSON doesn't seem to work. So far I got to try Orange and
> painlessjson. Using Orange all I got was a lot of compiler errors.
> Painlessjson did compile normally but just ignores all interface class
> members.
>
> This is the code I tried (I apologize for not formatting it, I have no
> idea how to do that):
> interface MyInterface {
>    int GetA();
> }
>
> class Foo: MyInterface {
>    int a;
>    int GetA() { return a; }
> }
>
> // maybe add a class Bar later which implements the same interface
>
> class Foobar {
>    MyInterface myBar = new Foo();
> }
>
> void main()
> {
>    // serialize it
> }

Based upon the name for 'GetA' I suspect you are comming from C#.
So let me put this into that context.

For C# ISerialize[0] interface is used to denote a class that can be 
serialized.

Most notably is that ISerialize has a method called GetObjectData which 
populates a data table SerializationInfo with enough information to 
perform deserialization.
There is also a special constructor applied to any serializable class so 
it can manually recreated. This is not possible to be called in D 
unfortunately. You will need an empty constructor a separate method to 
emulate this successfully.

Most importantly with D is knowing type sizes, offsets and of course if 
pointer. If it is a pointer is it an array? Again if so, the sizes and 
if pointer ext. ext.

Now if you want to look at how Java does it[1]. It is very similar to 
what I'm saying with how C# also does it.


Anyway to summise why D doesn't yet have something akin to Java or C#. 
Simply put, we generally work with the actual type not an interface. So 
libraries like Orange can serialize/deserialize with great certainty 
that it got everything.

However if you need any help with making such a library, please let me know!

[0] 
https://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable(v=vs.110).aspx
[1] http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html


More information about the Digitalmars-d-learn mailing list