我正在制作一个asp.net核心web api,我想以特定格式返回Ok(JsonList(我有以下对象的列表:
public class obj
{
string schoolName;
int studentscount;
int teacherscount;
}
默认情况下会序列化为:
[{"schoolName":"name_1",
"studentscount" : "5",
"teacherscount" : "2"
},
{"schoolName":"name_2",
"studentscount" : "10",
"teacherscount" : "3"
}]
我希望name属性是对象的名称:
[{
"name_1":{
"studentscount" : "5",
"teacherscount" : "2"
},
"name_2:"{
"studentscount" : "10",
"teacherscount" : "3"
}
}]
您可以创建一个新类并尝试这个
Dictionary<string, Counts> counts = JArray.Parse(json).ToDictionary(j => (string)j["schoolName"], j => new Counts
{
studentscount = (int)j["studentscount"],
teacherscount = (int)j["teacherscount"]
});
json = JsonConvert.SerializeObject(counts, Newtonsoft.Json.Formatting.Indented);
public class Counts
{
public int studentscount { get; set; }
public int teacherscount { get; set; }
}
结果
{
"name_1": {
"studentscount": 5,
"teacherscount": 2
},
"name_2": {
"studentscount": 10,
"teacherscount": 3
}
}
但如果出于某些原因,您仍然需要阵列
var countsArray = new List<Dictionary<string,Counts>> {counts};
json=JsonConvert.SerializeObject(countsArray,Newtonsoft.Json.Formatting.Indented);
结果
[
{
"name_1": {
"studentscount": 5,
"teacherscount": 2
},
"name_2": {
"studentscount": 10,
"teacherscount": 3
}
}
]