How to Convert JSON to ExpandoObject

In this example we will convert a JSON String to ExpandoObject. Start with an extension method that takes the json string value and converts it into a IDictionary. Then we use an extension method which processes each key value pair into the Expando Object.



public static ExpandoObject ToExpando(this string json)
{

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    IDictionary< string, object > dictionary = serializer.Deserialize< IDictionary< string, object> >(json);
    return dictionary.Expando();

}


public static ExpandoObject Expando(this IDictionary< string, object > dictionary)
{
    ExpandoObject expandoObject = new ExpandoObject();
    IDictionary< string, object > objects = expandoObject;

    foreach (var item in dictionary)
    {
        bool processed = false;

        if (item.Value is IDictionary< string, object >)
        {
            objects.Add(item.Key, Expando((IDictionary< string, object >)item.Value));
            processed = true;
        }
        else if (item.Value is ICollection)
        {
            List< object > itemList = new List< object >();

            foreach (var item2 in (ICollection)item.Value)

                if (item2 is IDictionary< string, object >)
                    itemList.Add(Expando((IDictionary< string, object >)item2));
                else
                    itemList.Add(Expando(new Dictionary< string, object > { { "Unknown", item2 } }));

            if (itemList.Count > 0)
            {
                objects.Add(item.Key, itemList);
                processed = true;
            }
        }

        if (!processed)
            objects.Add(item);
    }

    return expandoObject;
}


Comments

No comments yet.

Add Yours

  • Author Avatar

    YOU


Comment Arrow




About Author

Robert

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning hands down.