Dictionary to object in C#
Create an object from dictionary collection
Dictionaries are very useful as data holders for any type of the code in C#. You can easily manipulate data stored on collections, but there are disadvantages like posting data to REST JSON service.
The easiest way to invoke JSON REST API is to simply serialize your object to JSON string. For this kind of posting data dictionaries are not suitable, but if you have a look at dictionary structure you can see that it contains keys and values which can be easily converted to simple POCO object structure where you map key to property name of result object instance and map dictionary value to property value of result object.
This can be easy done with dynamic objects and ExpandoObject cass which is introduced in .NET Framework 4.
private static dynamic DictionaryToObject(IDictionary<String, Object> dictionary) { var expandoObj = new ExpandoObject(); var expandoObjCollection = (ICollection<KeyValuePair<String, Object>>)expandoObj; foreach (var keyValuePair in dictionary) { expandoObjCollection.Add(keyValuePair); } dynamic eoDynamic = expandoObj; return eoDynamic; }
Since dynamic object which is result of the method is not so convenient to use, you can simply specify the type you expect as a result with Generic type.
Wrapping the previous method this can be easily achieved and you keep the dynamic result method in case you do not need an additional step of casting to output type.
private static T DictionaryToObject<T>(IDictionary<String, Object> dictionary) where T : class { return DictionaryToObject(dictionary) as T; }
So now to use the code above for generating JON from a simple dictionary which we can use for example for REST API calls as mentioned at the top of this article:
static void Main(string[] args){IDictionary<String, Object> simpleDictionary = new Dictionary<String, Object>(){["Name"] = "Apple",["Weight"]=23,["Checked"] = true }; String result = JsonConvert.SerializeObject(DictionaryToObject(simpleDictionary),Formatting.Indented); Console.WriteLine(result); Console.ReadLine(); }
The result of the code will be the following JSON representing the runtime generated object instance:
{ "Name": "Apple", "Weight": 23, "Checked": true }
References
- https://msdn.microsoft.com/en-us/library/bb384067.aspx
- https://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=vs.110).aspx
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
Comments for this article