gpt4 book ai didi

c# - 使用自定义格式序列化 JSON 字符串

转载 作者:太空宇宙 更新时间:2023-11-03 18:39:05 24 4
gpt4 key购买 nike

我有一个 Generic List 对象,它在表格下方作为它自己的值。

CountryID | StateID | StateName
--------------------------------
1 | 1 | Alabama
1 | 2 | California
1 | 3 | Florida
1 | 4 | Hawaii
2 | 5 | London
2 | 6 | Oxford

我想根据那个 List 对象创建 JSON 字符串。我想要获取的 JSON 格式如下所示。

{           
1: { '1': 'Alabama', '2': 'California', '3': 'Florida', '4': 'Hawaii' },
2: { '5': 'London', '6': 'Oxford' }
};

我使用下面的类来生成 JSON 对象。

public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}

public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}

但是,当我完成调用 ToJSON 方法时得到的实际输出如下所示。

{
[

{"CountryID":1,"StateID":1,"StateName":"Alabama"},
{"CountryID":1,"StateID":2,"StateName":"California"},
{"CountryID":1,"StateID":3,"StateName":"Florida"},
{"CountryID":1,"StateID":4,"StateName":"Hawaii"},
{"CountryID":2,"StateID":5,"StateName":"London"},
{"CountryID":2,"StateID":6,"StateName":"Oxford"}

]
}

所以,谁能给我建议,我该如何制作我想要的 JSON 字符串格式?
我们将不胜感激。

最佳答案

似乎一个简单的方法是使用 LINQ 选择字典,然后将字典对象发送到 JavascriptSerializer...

如果我们有:

var list = new[]
{
new {CountryID = 1, StateID = 1, StateName = "Alabama"},
new {CountryID = 1, StateID = 2, StateName = "California"},
new {CountryID = 1, StateID = 3, StateName = "Florida"},
new {CountryID = 1, StateID = 4, StateName = "Hawaii"},
new {CountryID = 2, StateID = 5, StateName = "London"},
new {CountryID = 2, StateID = 6, StateName = "Oxford"}
};

然后我们可以在其上递归调用 .ToDictionary 以获得以下内容:

var d = list
.GroupBy(x=>x.CountryID)
.ToDictionary(g=> g.Key.ToString(),
g => g.ToDictionary(x => x.StateID.ToString(),x => x.StateName));

var serializer = new JavaScriptSerializer();
return serializer.Serialize(d);

它返回你请求的 JSON

注意:您必须在字典键上调用 .ToString(),因为 JavaScriptSerializer 似乎在键不是字符串的字典上失败...

关于c# - 使用自定义格式序列化 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11131818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com