我想使用JsonConvert。序列化,以便将c#数组类对象序列化为json非数组对象。
public list<<strong>雇员雇员;
输出:"{"employees":
{"name":"Alex","number":"25860340"},
{"name":"Tom","number":"94085345"}
}"
您在问题中所要求的格式将不是有效的JSON,因为对象不允许直接跟随另一个,除非它们是数组的一部分(参见JSON.org)。但是,您可以将员工列表转换为字典并将其序列化,只要使用合适的键即可。一个想法是使用员工编号作为键,例如:
var employees = new List<Employee>
{
new Employee { name = "Alex", number = "25860340" },
new Employee { name = "Tom", number = "94085345" }
};
var obj = new
{
employees = employees.ToDictionary(e => e.number)
};
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
Console.WriteLine(json);
这将给你这样的输出,这是接近你想要的:
{
"employees": {
"25860340": {
"name": "Alex",
"number": "25860340"
},
"94085345": {
"name": "Tom",
"number": "94085345"
}
}
}
如果员工编号实际上不是唯一的,则可以使用列表中每个员工的职位作为键,如下所示:
int i = 0;
var obj = new
{
employees = employees.ToDictionary(e => i++)
};
这会给你以下的输出:
{
"employees": {
"0": {
"name": "Alex",
"number": "25860340"
},
"1": {
"name": "Tom",
"number": "94085345"
}
}
}