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

I want to serialize a dynamic object in 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 this: {"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 get the JSON format I want?

+11
json c # serialization asp.net-mvc
Aug 12 2018-11-12T00:
source share
5 answers

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

I changed the dictionary name to "Fields" and then serializes Json.Net to create json that looks like this:

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

where Property1 and Property2 are dynamically added properties - i.e. dictionary keys

It would be ideal if I could get rid of the additional โ€œFieldsโ€ property, which encapsulates the rest, but I worked on this restriction.

+3
Jun 28 2018-12-12T00:
source share

I had the same problem and decided to fix it using the JSON.net serializer (Newtonsoft.Json) instead of using the JsonContent result. He then serialized my dynamic objects with normal properties compared to the "key" value of the "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})); 
+3
Apr 19 '14 at 18:24
source share

This will return you what you want.

 public JsonResult Edit() { return Json(new {abc = "ABC"}); } 
+1
Aug 12 '11 at 15:41
source share

You can always serialize a HashTable, its not dynamic, but it supports pairs of key values โ€‹โ€‹of an object.

0
Apr 08 '13 at 6:37
source share

It worked fine for me. You must 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; } 
0
Mar 18 '14 at 13:49
source share



All Articles