Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Deserialize Dictionary<string, object> to an object

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;
}
like image 278
Maksim Vi. Avatar asked Jan 22 '23 09:01

Maksim Vi.


2 Answers

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;
    }
}
like image 104
Jeremy Avatar answered Jan 27 '23 20:01

Jeremy


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 );
like image 43
µBio Avatar answered Jan 27 '23 22:01

µBio