How to flatten an ExpandoObject returned via JsonResult in asp.net mvc? How to flatten an ExpandoObject returned via JsonResult in asp.net mvc? json json

How to flatten an ExpandoObject returned via JsonResult in asp.net mvc?


Using JSON.NET you can call SerializeObject to "flatten" the expando object:

dynamic expando = new ExpandoObject();expando.name = "John Smith";expando.age = 30;var json = JsonConvert.SerializeObject(expando);

Will output:

{"name":"John Smith","age":30}

In the context of an ASP.NET MVC Controller, the result can be returned using the Content-method:

public class JsonController : Controller{    public ActionResult Data()    {        dynamic expando = new ExpandoObject();        expando.name = "John Smith";        expando.age = 30;        var json = JsonConvert.SerializeObject(expando);        return Content(json, "application/json");    }}


You could also, make a special JSONConverter that works only for ExpandoObject and then register it in an instance of JavaScriptSerializer. This way you could serialize arrays of expando,combinations of expando objects and ... until you find another kind of object that is not getting serialized correctly("the way u want"), then you make another Converter, or add another type to this one. Hope this helps.

using System.Web.Script.Serialization;    public class ExpandoJSONConverter : JavaScriptConverter{    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)    {        throw new NotImplementedException();    }    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)    {                 var result = new Dictionary<string, object>();        var dictionary = obj as IDictionary<string, object>;        foreach (var item in dictionary)            result.Add(item.Key, item.Value);        return result;    }    public override IEnumerable<Type> SupportedTypes    {        get         {               return new ReadOnlyCollection<Type>(new Type[] { typeof(System.Dynamic.ExpandoObject) });        }    }}

Using converter

var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new JavaScriptConverter[] { new ExpandoJSONConverter()});var json = serializer.Serialize(obj);


Here's what I did to achieve the behavior you're describing:

dynamic expando = new ExpandoObject();expando.Blah = 42;expando.Foo = "test";...var d = expando as IDictionary<string, object>;d.Add("SomeProp", SomeValueOrClass);// After you've added the properties you would like.d = d.ToDictionary(x => x.Key, x => x.Value);return new JsonResult(d);

The cost is that you're making a copy of the data before serializing it.