How to convert ExpandoObject to JSON

In this example we will convert an ExpandoObject to JSON string using an Extension method. This is done by looping over the key value pairs in the Expando Object and using the JavaScriptSerializer to serialize the value property.


public static class ExpandoObjectExtensions
{
    public static string ToJson(this ExpandoObject expando)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        StringBuilder json = new StringBuilder();
        List< string > keyPairs = new List< string >();
        IDictionary< string, object > dictionary = expando as IDictionary< string, object >;
        json.Append("{");

        foreach (KeyValuePair< string, object > pair in dictionary)
        {
            if(pair.Value is ExpandoObject)
            {
                keyPairs.Add(String.Format(@"""{0}"": {1}", pair.Key, (pair.Value as ExpandoObject).ToJson()));    
            }
            else
            {
                keyPairs.Add(String.Format(@"""{0}"": {1}", pair.Key, serializer.Serialize(pair.Value)));    
            }                
        }

        json.Append(String.Join(",", keyPairs.ToArray()));
        json.Append("}");

        return json.ToString();
    }
}


Comments

  1. J S L Geeganage April 20th

    Comment Arrow

    Thank you. This save my time.


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.