Convert DataTable to JSON with key per row

后端 未结 2 1407
[愿得一人]
[愿得一人] 2020-12-02 01:48

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 followi

2条回答
  •  温柔的废话
    2020-12-02 02:28

    Using JSON.NET (Newtonsoft.Json.Linq)

    var obj = new JObject(
        dataTable.Rows.Cast()
             .Select(r => new JProperty(r["ID"].ToString(),
                     new JObject(
                         new JProperty("Name", r["Name"].ToString()),
                         new JProperty("Active", r["Active"].ToString())
                     )
                 ))
    );
    
    // Convert the JObject to a JSON string
    var json = obj.ToString();
    

提交回复
热议问题