4

If I have an IDictionary<string, string> MyDictionary that resembles this:

{
    {"foo", "bar"},
    {"abc", "xyz"}
}

and in my MVC controller I have a method like so:

[HttpPost]
public JsonResult DoStuff()
{
    return Json(MyDictionary);
}

...it sends back something like:

[
 {"Key":"foo", "Value":"bar"},
 {"Key":"abc", "Value":"xyz"}
]

I was expecting (and wanting) something like:

{
 "foo":"bar",
 "abc":"xyz"
}

How can I accomplish this?

UPDATE

So this is directly related to the fact that this project was upgraded from an ASP.NET 2.0 application that used a custom JSON serializer; apparently, for backwards compatibility, they made that the default JSON serializer in the MVC application. Ultimately I overrode that behavior in my controller with the Json.NET result, and my problem was solved.

4

1 Answer 1

4

With the default Json serializer(Json.Net), It should return you the below JSON structure from a Dictionary<string, string>

{"Foo": "TTTDic", "Bar": "Scoo"}

With your action method:

[HttpPost]
public JsonResult DoStuff()
{
    var MyDictionary = new Dictionary<string, string>();
    MyDictionary.Add("Foo", "TTTDic");
    MyDictionary.Add("Bar", "Scoo");
    return Json(MyDictionary);
}

Verified this in MVC5 and MVC6.

If you are still having problems, why not create a simple POCO with the properties you want?

public class KeyValueItem
{
    public string Foo { set; get; }
    public string Abc { set; get; }
}

And create an object of that, set the property values and send that as JSON.

[HttpPost]
public JsonResult DoStuff()
{
  var item = new KeyValueItem
  {
      Foo="Bee",
      Abc="Scoo"
  };
  return Json(item );
}
Sign up to request clarification or add additional context in comments.

4 Comments

Only a note: The POCO would only work if the dictionary is made of a concrete object. Usually people use Dictionaries like that for dynamic values.
Exactly my situation; I cannot use a POCO in this case as the "properties" are dynamic.
What version is yours ? I verified it in MVC5 and 6 It converts the dictionary to the JSON format you want.
Looks like when this application was upgraded to MVC5 from the legacy ASP.NET, they purposely specified a custom json serializer for backwards compatibility (they were using it before the upgrade). I'll mark this as the answer, since it got me on the right track on what to look for. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.