如何使用变量值将列表<对象>序列化为 JSON

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

本文关键字:对象 序列化 JSON 何使用 变量值 列表      更新时间:2023-09-26

>我需要序列化对象列表,但不使用"默认方式":

假设我在 C# 中有这个类:

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

如果我序列化此列表(return Json(tests.ToArray())),我会得到这个

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

取而代之的是,我想要这个结果:

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

编辑:

这是所需的输出:

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

我希望第一个变量的内容是JS属性名称,第二个变量是其值。

有什么想法吗?我已经看到了这个解决方案:

如何在 C# 中将字典转换为 JSON 字符串?

但我不想将我的对象列表转换为字典,以便我可以使用该 string.format 解决方案再次转换它。

谢谢!

如果您使用的是 JSON.Net(我假设您使用的是MVC 5),则可以将列表转换为

List<Dictionary<string, string>>

每个列表条目都应该是一个新的词典,该词典中有一个词条。 JSON.Net 会将属性名称替换为字典键值,从而提供所需的结构。

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

生成以下 JSON:

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

编辑:

要反映所需的解决方案,请执行以下操作:

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

这是一种更通用的方法,不需要列表(只是一个 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);