我正在尝试使用 json.net 序列化一组对象
对象看起来像这样:
public class TaxBand
{
public TaxBand(string county, decimal taxPercentage)
{
County = county;
Tax = taxPercentage;
}
public string County { get; private set; }
public decimal Tax { get; private set; }
}
它们包含在这样的结构中:
var data = new Dictionary<string, List<TaxBand>>();
data = PopulateDataset();
string json = JsonConvert.SerializeObject(data, Formatting.Indented);
这会生成如下所示的 json:
{
"North": [
{
"County": "Merseyside",
"Tax": 5.0
},
{
"County": "Greater Manchester",
"Tax": 6.0
}
],
"South": [
{
"County": "Greater London",
"Tax": 5.5
},
{
"County": "Surry",
"Tax": 6.2
}
]
}
是否可以生成如下所示的 json:
{
"North":
{
"Merseyside": 5.0,
"Greater Manchester" : 6.0
},
"South":
{
"Greater London": 5.5,
"Surry": 6.2
}
}
我很乐意考虑改变任何对象的形状,或者确实使用不同的序列化库
最佳答案
在一些Linq的帮助下
var data = new Dictionary<string, List<TaxBand>>();
data = PopulateDataset();
var data2 = data.ToDictionary(kv => kv.Key,
kv => kv.Value.ToDictionary(t=>t.County,t=>t.Tax) );
var s = JsonConvert.SerializeObject(data2,Newtonsoft.Json.Formatting.Indented);
输出:
{
"North": {
"Merseyside": 5.0,
"Greater Manchester": 6.0
},
"South": {
"Greater London": 5.5,
"Surry": 6.2
}
}
关于c# - json序列化格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11774926/