eestein
eestein

Reputation: 5114

How to serialize List<object> to JSON using variable value?

I need to serialize a list of objects, but not using the "default way":

Let's say I have this class in C#:

public class Test
{
    public string Key;
    public string Value;
}
List<Test> tests;

If I serialize this list (return Json(tests.ToArray())) I get this

{"Key": "vKey1", "Value": "value1"}, {"Key": "vKey2", "Value": "value2"}

Instead of that, I want this result:

{"vKey1": "value1"}, {"vKey2": "value2"}

EDIT:

This is the desired output:

{"vKey1": "value1", "vKey2": "value2"}

I want the first variable's content to be the JS property name and the second one its value.

Any ideas? I've seen this solution:

How do I convert a dictionary to a JSON String in C#?

but I don't wanna transform my object list into a dictionary so I could transform it again using that string.format solution.

Thanks!

Upvotes: 0

Views: 1715

Answers (2)

jimSampica
jimSampica

Reputation: 12410

This is a more generalized approach without the need for a List (just an IEnumerable).

var tests = new List<Test>
{
    new Test {Key = "vKey1", Value = "value1"},
    new Test {Key = "vKey2", Value = "value2"}
};

var dict = tests.ToDictionary(t => t.Key, t => t.Value);

return Json(dict);

Upvotes: 1

David L
David L

Reputation: 33833

If you are using JSON.Net (and I assume you are since you are using MVC 5), you can transform your list into a

List<Dictionary<string, string>>

Each list entry should be a new dictionary with one entry in that dictionary. JSON.Net will replace the property name with your dictionary key value, giving you the structure that you need.

public ActionResult Test()
{
    tests = new List<Test>
    {
        new Test {Key = "vKey1", Value = "value1"},
        new Test {Key = "vKey2", Value = "value2"}
    };

    var tests2 = new List<Dictionary<string, string>>();

    tests.ForEach(x => tests2.Add(new Dictionary<string, string>
    {
        { x.Key, x.Value }
    }));

    return Json(tests2, JsonRequestBehavior.AllowGet);
}

Produces the following JSON:

[{"vKey1":"value1"},{"vKey2":"value2"}]

EDIT:

To reflect the desired solution:

tests.ForEach(x => tests2.Add(x.Name, x.Value));

Upvotes: 1

Related Questions