数据表转换成JSON,每行按键 [英] Convert DataTable to JSON with key per row

查看:202
本文介绍了数据表转换成JSON,每行按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想下面的是一个很常见的任务,并假定会有它一个简单的解决方案,但我不能找到一个。

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

我想序列化作为一个JSON对象,其中的ID列是JSON对象就像一个节点:

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"
        }
    }
]

我看着JSON.NET但不能得到它的工作。
编辑:我使用C#

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

推荐答案

这是JSON.NET很简单。只需将您的数据表到字典相当于字典:

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);

下面是完整的测试:

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"));

和结果:

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

这篇关于数据表转换成JSON,每行按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆