std.serialization: pre-voting review / discussion

Jacob Carlborg doob at me.com
Fri Aug 23 13:28:10 PDT 2013


On 2013-08-22 21:30, ilya-stromberg wrote:

> Great! What about more difficult cases? For example, we have:
>
> class Foo
> {
>     int a;
>     int b;
> }
>
> After changes we have new class:
>
> class Foo
> {
>     long b;
> }
>
> Can std.serialization load data to new class from old file? It should
> ignore "a" and convert "b" from int to long.

Actually, my previous answer was not entirely correct. By default it 
will throw an exception. But you can implement the above using custom 
serialization (here using Orange) :

module main;

import orange.serialization._;
import orange.serialization.archives._;

import std.stdio;

class Foo : Serializable
{
     long b;

     void toData (Serializer serializer, Serializer.Data key)
     {
     }

     void fromData (Serializer serializer, Serializer.Data key)
     {
         b = serializer.deserialize!(int)("b");
     }
}

void main ()
{
     auto archive = new XmlArchive!(char);
     auto serializer = new Serializer(archive);

     auto data = `<?xml version="1.0" encoding="UTF-8"?>
     <archive version="1.0.0" type="org.dsource.orange.xml">
         <data>
             <object runtimeType="main.Foo" type="main.Foo" key="0" id="0">
                 <int key="a" id="1">3</int>
                 <int key="b" id="2">4</int>
             </object>
         </data>
     </archive>`;

     auto f = serializer.deserialize!(Foo)(cast(immutable(void)[]) data);
     assert(f.b == 4);
}

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list