Skip to content

Instantly share code, notes, and snippets.

@renanvieira
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renanvieira/e26dc34e2de156723f79 to your computer and use it in GitHub Desktop.
Save renanvieira/e26dc34e2de156723f79 to your computer and use it in GitHub Desktop.
ExpandoObject recursive extension method for JSON serialization
/*
*Original version posted by TimDog in a StackOverflow question: http://stackoverflow.com/questions/5156664/how-to-flatten-an-expandoobject-returned-via-jsonresult-in-asp-net-mvc
*/
public static class DynamicObjectHelper
{
public static string Flatten(this ExpandoObject expando)
{
return FlattenImplementation(expando);
}
private static string FlattenImplementation(ExpandoObject expando)
{
StringBuilder sb = new StringBuilder();
List<string> contents = new List<string>();
var d = expando as IDictionary<string, object>;
sb.Append("{");
JsonSerializerSettings settings = new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
};
foreach (KeyValuePair<string, object> kvp in d)
{
if (kvp.Value is ExpandoObject)
{
contents.Add(String.Format("\"{0}\": {1}", kvp.Key, FlattenImplementation(kvp.Value as ExpandoObject)));
}
else
{
contents.Add(String.Format("\"{0}\": {1}", kvp.Key, JsonConvert.SerializeObject(kvp.Value, settings)));
}
}
sb.Append(String.Join(",", contents.ToArray()));
sb.Append("}");
return sb.ToString();
}
}
@renanvieira
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment