如何在C#MVC Controller操作中将动态对象序列化为JSON?

pan*_*wel 12 c# asp.net-mvc serialization json

我想将动态对象序列化为JSON.我尝试使用ExpandoObject,但结果不是我需要的:

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

我希望JSON看起来像:{"abc":"ABC"}但它看起来像[{"Key":"abc","Value":"ABC"}]显然ExpandoObject不会这样做,但我可以继承吗从DynamicObject以某种方式覆盖其方法来实现我想要的JSON格式?

小智 7

我有同样的问题,最后通过使用JSON.net(Newtonsoft.Json)序列化程序而不是使用JsonContent结果来修复它.然后它将我的动态对象序列化为普通属性,而不是"key""value"怪异列表.

//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}));
Run Code Online (Sandbox Code Playgroud)


sco*_*ttm 3

这将返回你想要的。

public JsonResult Edit()
{   
    return Json(new {abc = "ABC"});
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个具有 abc 属性的类。我希望该类在运行时添加属性。 (3认同)