Last active
August 29, 2015 14:20
ExpandoObject recursive extension method for JSON serialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
*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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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