[英]Datatable with Parent and Child to JSON format with Hierarchy
I am trying to build a JSON output from the C# datatable. 我正在尝试从C#数据表构建JSON输出。 The single datatable contains parent and child as well.
单个数据表也包含父级和子级。 I would like to use LINQ to setup the JSON data, but would like to avoid creating classes since I have many such requirements and creating classes for each will be a burden.
我想使用LINQ来设置JSON数据,但是想避免创建类,因为我有很多这样的要求,而为每个类创建类将是一个负担。
Code 码
var obj = dt.AsEnumerable()
.GroupBy(r => r["Head"])
.ToDictionary(g => g.Key.ToString(),
g => g.Select(r => new {
item = r["Item"].ToString(),
quantity = (int)r["Quantity"]
})
.ToArray());
var json = JsonConvert.SerializeObject(obj);
The above code provides the following output, 上面的代码提供以下输出,
{
Sports : [
{item: 'Porsche 911', quantity: 100},
{item: 'Porsche 912', quantity: 200}
],
Luxury : [
{item: 'BMW 3 Series', quantity: 300}
],
Small :[
{item: 'Toyota Corolla', quantity: 400},
{item: 'Mitsubishi Lancer', quantity: 500},
{item: 'Mitsubishi Lancer 2', quantity: 600}
]}
But I want the following output 但是我想要以下输出
[
{
Head: 'Sports',
total: 300,
data : [
{item: 'Porsche 911', quantity: 100},
{item: 'Porsche 912', quantity: 200}
]
},
{
Head: 'Luxury',
total: 300,
data : [
{item: 'BMW 3 Series', quantity: 300}
]
},
{
Head: 'Small',
total: 1500,
data :[
{item: 'Toyota Corolla', quantity: 400},
{item: 'Mitsubishi Lancer', quantity: 500},
{item: 'Mitsubishi Lancer 2', quantity: 600}
]
}
]
This post is a copy from Datatable with Parent and Child to JSON format . 这篇文章是从Datatable with Parent and Child到JSON格式的副本。 I wanted the data in a different format.
我想要其他格式的数据。
It can be written like this: 可以这样写:
var obj = dt.AsEnumerable()
.GroupBy(r => r["Head"])
.Select(g => new
{
Head = g.Key.ToString(),
total = g.Sum(x => (int)x["Quantity"]),
data = g.Select(r => new
{
item = r["Item"].ToString(),
quantity = (int)r["Quantity"]
}).ToArray()
})
.ToList();
var json = JsonConvert.SerializeObject(obj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.