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

耗尽温柔 提交于 2020-01-01 04:26:05

问题


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?


回答1:


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}));



回答2:


This may not be useful to you, but I had a similar requirement, but used a SerializableDynamicObject

I changed the name of the dictionary to "Fields" and then this serializes with Json.Net to produce json which looks like:

  {"Fields":{"Property1":"Value1", "Property2":"Value2" etc.

where Property1 and Property2 are Dynamically added properties - i.e. Dictionary Keys

It would be perfect if I could get rid of the extra "Fields" property which encapsulates the rest, but I've worked around that limitation.




回答3:


This will return what you want.

public JsonResult Edit()
{   
    return Json(new {abc = "ABC"});
}



回答4:


You can always serialize a HashTable, its not dynamic but it supports object key value pairs.




回答5:


This worked for me perfectly. You have to use Json.NET.

 [HttpGet]
    public string GetJson()
    {
        List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();

        List<DataEntry> properties = new List<DataEntry>();

        for (int i = 0; i < 10; i++)
        {
            properties.Add(new DataEntry { Column = "column" + i.ToString(), Value = "value" + i.ToString() });
        }

        list.Add(properties.ToDictionary(x => x.Column, y => y.Value));
        string test = JsonConvert.SerializeObject(list);

        return test;
    }


来源:https://stackoverflow.com/questions/7041902/how-can-i-serialize-dynamic-object-to-json-in-c-sharp-mvc-controller-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!