本文介绍了使用每行键将 DataTable 转换为 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为以下是一项非常常见的任务,并假设有一个简单的解决方案,但我找不到.

如果我有以下结构的数据表.

ID 名称 有效ID1 约翰 TRUEID2 账单错误

我想将其序列化为 JSON 对象,其中 ID 列是 JSON 对象中的一个节点,例如:

[{ID1":{"姓名": "约翰",主动":真实"},ID2":{"姓名": "比尔",主动":假"}}]

我查看了 JSON.NET,但无法让它工作.我正在使用 C#

解决方案

这对于 JSON.NET 来说非常简单.只需将您的数据表转换为等效的字典字典:

public Dictionary>DatatableToDictionary(DataTable dt, 字符串 id){var cols = dt.Columns.Cast().Where(c => c.ColumnName != id);返回 dt.Rows.Cast().ToDictionary(r => r[id].ToString(),r=>cols.ToDictionary(c => c.ColumnName, c => r[c.ColumnName]));}

然后调用:

JsonConvert.SerializeObject(DatatableToDictionary(dt, "ID"), Newtonsoft.Json.Formatting.Indented);

这是完整的测试:

var dt = new DataTable("MyTable");dt.Columns.Add("ID");dt.Columns.Add("名称");dt.Columns.Add("Active");dt.LoadDataRow(new[] {"ID1", "John", "True"}, true);dt.LoadDataRow(new[] {"ID2", "Bill", "False"}, true);JsonConvert.SerializeObject(DatatableToDictionary(dt, "ID"));

结果:

{ID1":{"姓名": "约翰",主动":真实"},ID2":{"姓名": "比尔",主动":假"}}

I thought the following would be a pretty common task and assumed there would be an easy solution for it, but i can't find one.

If I have a datatable in the following structure.

ID  Name    Active
ID1 John    TRUE
ID2 Bill    FALSE

I would like to serialize it as a JSON object where the ID column is a node in the JSON object like:

[
    {
        "ID1": {
            "Name": "John",
            "Active": "True"
        },
        "ID2": {
            "Name": "Bill",
            "Active": "False"
        }
    }
]

I looked into JSON.NET but could not get it to work.Edit: I'm using C#

解决方案

This is quite simple with JSON.NET. Just convert your data table into the equivalent dictionary of dictionaries:

public Dictionary<string, Dictionary<string, object>> DatatableToDictionary(DataTable dt, string id)
{
    var cols = dt.Columns.Cast<DataColumn>().Where(c => c.ColumnName != id);
    return dt.Rows.Cast<DataRow>()
             .ToDictionary(r => r[id].ToString(),
                           r => cols.ToDictionary(c => c.ColumnName, c => r[c.ColumnName]));
}

Then call:

JsonConvert.SerializeObject(DatatableToDictionary(dt, "ID"), Newtonsoft.Json.Formatting.Indented);

Here's the full test:

var dt = new DataTable("MyTable");
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Columns.Add("Active");

dt.LoadDataRow(new[] {"ID1", "John", "True"}, true);
dt.LoadDataRow(new[] {"ID2", "Bill", "False"}, true);

JsonConvert.SerializeObject(DatatableToDictionary(dt, "ID"));

And the result:

{
  "ID1": {
    "Name": "John",
    "Active": "True"
  },
  "ID2": {
    "Name": "Bill",
    "Active": "False"
  }
}

这篇关于使用每行键将 DataTable 转换为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:08
查看更多