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(); } }
Andre March 26th
Works perfect! Thank you!!!
J S L Geeganage April 20th
Thank you. This save my time.
Add Yours
YOU