I'm receiving data in dictionary form and would like to deserialize it into a dynamic object. The twist is the dictionary keys express a hierarchical object. A second twist is some of the keys express an array and/or dictionary property.
For example:
===========Key================ ======Value========
Person.First | John
Person.Last | Doe
Person.Phone[Work] | 999-555-1234
Person.Phone[Home] | 999-555-1235
Person.Addresses[Home].Street | 101 My Street
Person.Addresses[Home].City | AnyTown
Person.Spouse.First | Jane
Person.Spouse.Last | Doe
Person.Insurance[0].Name | Medicare
Person.Insurance[0].GroupNum | 1234567
Edit: Added array examples
I'm trying to find a simple method to create an object that can then be used in a runtime expressions evaluator.
Here's my first attempt that works for the simple properties, but doesn't attempt to handle the arrays
public static class DynamicBuilder
{
public static object Build(IDictionary<string, object> dict)
{
ExpandoObject root = new ExpandoObject();
foreach (var item in dict)
{
var objDict = (IDictionary<string, object>)root;
var parts = item.Key.Split('.');
for (int i = 0; i < parts.Length ; i++)
{
string propName = parts[i];
if (i < parts.Length - 1)
{
if (!objDict.ContainsKey(propName))
{
dynamic temp = new ExpandoObject();
objDict.Add(propName, temp);
objDict = (IDictionary<string, object>)temp;
}
else
{
objDict = (IDictionary<string, object>)objDict[propName];
}
}
else
{
if (objDict.ContainsKey(propName))
objDict[propName] = item.Value;
else
objDict.Add(propName, item.Value);
}
}
}
return root;
}
}
Any ideas on better way to approach this?
Thanks,