views:

21

answers:

1

Hi, I have a simple class in asp.net mvc that looks like this:

 public class JsonResponseItem
{
    public string Key { get; set; }
    public string Value { get; set; }

    public JsonResponseItem(string key, string value)
    {
        Key = key;
        Value = value;
    }
}

In my controllers I create a list of that type

    List<JsonResponseItem> response = new List<JsonResponseItem>();

so I can easily manage and add to the Json response. A dictionary object is kind of hard to do that with.

When I return the json object

 return Json(response);

It deserializes it so I have to reference everything by index first, because of the list. So if I had a property called "IsValid" I would have to reference it like this "IsValid[0]". I have way too much javascript code to make these changes.

How could I deserialize the JsonResponseItem class so I don't need the index reference in there?

Thanks!

+2  A: 

A Dictionary<string, string> would serialize into exactly the Json you're asking for. If you don't want to expose directly a dictionary, wrap it around in another class or use Json(response.ToDictionary(item => item.Key).

Julien Lebosquain
Originally I used a Dictionary, but now it is becoming a pain because I would need to constantly merge dictionaries and that seems to be a problem in of itself. It is so much easier to do it with a list, but I now have the problem of serialization.
chobo
Actually the response.ToDictionary() method is exactly what I needed. I just didn't fully understand what you meant by it.
chobo