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?
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}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With