可以使用父级和子级将数据转换为具有层次结构的JSON格式 [英] Datatable with Parent and Child to JSON format with Hierarchy
本文介绍了可以使用父级和子级将数据转换为具有层次结构的JSON格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码
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 [数量]
})
.ToArray());
var json = JsonConvert.SerializeObject(obj);
上述代码提供以下输出,
{
运动:[
{item:'保时捷911',数量:100},
{item:'保时捷912',数量: 200 b
$ b豪华:[
{item:'宝马3系',数量:300}
],
小:[
{项目:Toyota Corolla,数量:400},
{item:'Mitsubishi Lancer',数量:500},
{item:'Mitsubishi Lancer 2',数量:600}
]}
但是我想要以下输出
[
pre>
{
头:'运动',
总数:300,
数据:[
{item:保时捷911',数量:100},
{item:'保时捷912',数量:200}
]
},
{
头: ,
总数:300,
数据:[
{item:'宝马3系',数量:300}
]
},
{
头:小,
总数:1500,
数据:[
{item:'丰田卡罗拉',数量:400},
{item:'Mitsubishi Lancer'数量:500},
{item:'Mitsubishi Lancer 2',数量:600}
]
}
]
这篇文章是从可以将父和子数据转换为JSON格式。我想以不同格式的数据。
解决方案可以这样写:
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);
I am trying to build a JSON output from the C# datatable. 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.
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 . 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);
这篇关于可以使用父级和子级将数据转换为具有层次结构的JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文