使用JSON提供此数据:
[
{
"section": "charges",
"lines": [
{
"cardtype": "MasterCard"
},
{
"sales": "$16.55"
},
{
"items": "10"
},
{
"cardtype": "Visa"
},
{
"sales": "$16.50"
},
{
"items": "39"
},
{
"cardtype": "Diners"
},
{
"sales": "40.00"
},
{
"items": "10"
}
]
}
]
我想介绍属性名称并列出属性值-也许在DataTable中?
数据收集为Dictionary<string,object>()
我需要按卡类型汇总销售和商品计数。例如:
+---------------+-------+-------+
| cardtype | sales | items |
+---------------+-------+-------+
| Mastercard | 16.55 | 10 |
| Visa | 16.50 | 39 |
| Diners | 40.00 | 10 |
+---------------+-------+-------+
| Total | 73.05 | 59 | <- would be calculated after conversion.
+ --------------- + ------- + ------- +
我已经测试过SelectTokens()
方法,并且可以拉出行的数组,但是事实证明枢轴转换很困难,因为字段名称会根据数据的来源而有所不同。
有什么想法吗?
答案 0 :(得分:1)
尝试以下代码
var files = JArray.Parse(JSON);
var recList = files.SelectToken("$..lines");
var str = JsonConvert.SerializeObject(recList);
var regex = new System.Text.RegularExpressions.Regex(@"(\{[^}]+)\},\{([^}]+)\},\{([^}]+)\}");
var output = regex.Replace(str, "$1, $2, $3 }");
System.Data.DataTable dt = (System.Data.DataTable)JsonConvert.DeserializeObject(str, (typeof(System.Data.DataTable)));