panpawel
panpawel

Reputation: 1848

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

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?

Upvotes: 14

Views: 28826

Answers (5)

Matt Watson
Matt Watson

Reputation: 1000

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

Upvotes: 8

VIctor Hugo
VIctor Hugo

Reputation: 39

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

Upvotes: 0

Roy
Roy

Reputation: 428

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

Upvotes: 0

BonyT
BonyT

Reputation: 10940

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.

Upvotes: 3

scottm
scottm

Reputation: 28701

This will return what you want.

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

Upvotes: 3

Related Questions