What would be the best way to deserialize this
Dictionary<string, object>{
{"fName", "John"},
{"lName", "Doe"},
{"email", "[email protected]"}
}
to this
class Member{
string fName;
string lName;
string email;
}
NewtonSoft has become so common in ASP.NET applications these days that if I needed a short and sweet solution to this type of mapping I could use some code like this. Sure it might be abusive to introduce a third party library if its not already present, but sometimes we just use what works. And Newtonsoft does!
using Newtonsoft.Json;
class SerializationTests
{
public void DictionarySerializeSample()
{
var dict = new Dictionary<string, object>
{
{"fName", "John"},
{"lName", "Doe"},
{"email", "[email protected]"}
};
string dictInJson = JsonConvert.SerializeObject(dict);
var member = JsonConvert.DeserializeObject<Member>(dictInJson);
// use Newtonsoft to write out the object re-serialized
Console.WriteLine(JsonConvert.SerializeObject(member, Formatting.Indented));
}
public class Member
{
public string fName;
public string lName;
public string email;
}
}
This isn't really serialization in the normal sense, that usually refers to taking some disk or network formatted data (binary, ASCII, JSON etc) and loading it into a runtime object.
However, if I understand you correctly, I think what you are trying to do is...
public Member( Dictionary<string,object> dictionary )
{
fName = dictionary["fName"];
lName = dictionary["lName"];
email = dictionary["email"];
}
// usage Member m = new Member( inputDictionary );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With