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:
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:
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:
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:
I did also try with MessagePack: https://msgpack.org, but I can't make it to go below one level either:
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?