I want to serialize dynamic object to JSON. I tried using ExpandoObject, but the result is not what I need:
开发者_Python百科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}));
This will return what you want.
public JsonResult Edit()
{
return Json(new {abc = "ABC"});
}
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.
You can always serialize a HashTable, its not dynamic but it supports object key value pairs.
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;
}
精彩评论