Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I serialize dynamic object to JSON in C# MVC Controller action?

I want to serialize dynamic object to JSON. I tried using ExpandoObject, but the result is not what I need:

public JsonResult Edit()
{   
    dynamic o = new ExpandoObject();
    ((IDictionary<string,Object>)o)["abc"] = "ABC"; //or o.abc = "ABC";
    return Json(o);
}

I want JSON to look like: {"abc": "ABC"} but instead it looks like [{"Key":"abc","Value":"ABC"}] Obviously ExpandoObject will not do, but can I inherit from DynamicObject and somehow override its methods to achieve JSON format I want?

like image 476
panpawel Avatar asked Aug 12 '11 14:08

panpawel


1 Answers

I had this same problem and ended up fixing it by using the JSON.net (Newtonsoft.Json) serializer instead of using the JsonContent result. It then serialized my dynamic objects with normal properties versus the "key" "value" weird list.

//In my usage I had a list of dynamic objects
var output = new List<dynamic>();

//Change this
return JsonContent(new {Error = errorMessage, Results = output});

//to this
return Content(JsonConvert.SerializeObject(new {Error = errorMessage, Results = output}));
like image 192
Matt Watson Avatar answered Sep 18 '22 15:09

Matt Watson