Hashtable serialization without BinaryFormatter?

163 Views Asked by At

I used BinaryFormatter which is now obsolete, to (de)serialize Hashtable objects.

Hashtables are tricky as they can wrap anything, including other Hashtables:

[ "fruits": [ "apple":10, "peach":4, "raspberry":5 ], "vegetables": [ "lettuce":5 ]
  "animals": [ "with4legs": [ "cat":15, "dog":2 ], "withwings": [ "bird":51 ]
]

BinaryFormatter could perfectly serialize these Hashtables (under dotNET 4.8):

Hashtable main = new Hashtable();

Hashtable fruits = new Hashtable()
{
    { "apple", 10 },
    { "peach", 4 },
    { "raspberry", 5 }
};
Hashtable vegetables = new Hashtable()
{
    { "lettuce", 5 }
};
Hashtable with4legs = new Hashtable()
{
    { "cat", 15 },
    { "dog", 2 }
};
Hashtable withwings = new Hashtable()
{
    { "bird", 51 }
};
Hashtable animals = new Hashtable()
{
    { "with4legs", with4legs },
    { "withwings", withwings }
};

main.Add("fruits", fruits);
main.Add("vegetable", vegetables);
main.Add("animals", animals);

BinaryFormatter binaryFormatter = new BinaryFormatter();
using (Stream stream = new FileStream("Test.file", FileMode.Create))
{
    binaryFormatter.Serialize(stream, main);
}

The file is somewhat messy:

enter image description here

However, when reading it back with the BinaryFormatter:

Hashtable newMain = new Hashtable();
using (Stream stream = new FileStream("Test.file", FileMode.OpenOrCreate))
{
    newMain = (Hashtable)binaryFormatter.Deserialize(stream);
}

It could perfectly reassemble the Hashtable:

enter image description here

Now, with dotNET, BinaryFormatter is obsolete, and XmlSerializer or JsonSerializer is recommended to be used instead:

using (Stream stream = new FileStream("Test.file", FileMode.Create))
{
    JsonSerializer.Serialize(stream, main);
}

File is in JSON format now:

enter image description here

And unfortunately when deserializing it:

Hashtable newMain = new Hashtable();
using (Stream stream = new FileStream("Test.file", FileMode.OpenOrCreate))
{
    newMain = (Hashtable)JsonSerializer.Deserialize<Hashtable>(stream);
}

Hashtable loses its structure:

enter image description here

I did also try with MessagePack: https://msgpack.org, but I can't make it to go below one level either:

enter image description here

Now I know there can be more efficient or robust solution for this than Hashtable, but still, is there a way to move from BinaryFormatter to any recommendation which can handle saving and reloading this structure?

0

There are 0 best solutions below