【问题标题】:How to convert the following data from a DataTable to a JSON object如何将以下数据从 DataTable 转换为 JSON 对象
【发布时间】:2018-01-07 13:01:39
【问题描述】:

目前我正在从数据库中获取以下格式的数据,并将其存储在 DataTable 中。

当前格式的数据:

Block   HouseNo   ResidentId
  A       101        1
  A       102        2
  A       103        3   
  B       101        4
  B       102        5  
  B       104        6

我想将其转换为以下格式的 JSON 对象。

要求格式:

{
    "Block A" : [{1:"101"},{2:"102"},{3:"103"}],
    "Block B" : [{4:"101"},{5:"102"},{6:"104"}] 
}

我已经编辑了上述格式。你能帮我得到想要的结果吗?

【问题讨论】:

  • 这个想法很简单:检索初始数据,转换数据,将结果格式化为 JSON。现在,其中哪一部分有问题?
  • 他是新手,因为他提到我认为这更好地帮助
  • 但我也想获得不同的值。你能建议一下吗?
  • 不幸的是,您的问题因重复而关闭...
  • 链接的答案 Convert datatable to JSON in C# 似乎不是特别相关,所以我继续重新打开它。

标签: c# asp.net json linq


【解决方案1】:

实现所需结果的一种方法是使用 Json.Net 的 LINQ-to-JSON API。以下是你的做法:

// Create a new JObject by grouping the data table rows by block and then
// selecting the groups into JProperties where the block is the property name
// and the property value is a JArray containing JObjects with the resident IDs 
// and corresponding house numbers in the group making up the properties of those. 

var obj = new JObject(
    table.Rows.Cast<DataRow>()
         .GroupBy(r => r["Block"])
         .Select(g => new JProperty("Block " + g.Key,
             new JArray(g.Select(r =>
                 new JObject(
                     new JProperty(r["ResidentId"].ToString(), r["HouseNo"])
                 )
             ))
         ))
);

// Convert the JObject to a JSON string
var json = obj.ToString();

工作演示:https://dotnetfiddle.net/smb9oW

【讨论】:

  • 这太有帮助了.. 非常感谢@Brian!
  • var obj = new JObject(table.Rows.Cast() .GroupBy(r => r["Block"]) .Select(g => new JProperty("Block" + g.Key, new JArray(g.Select(r => new JObject(new JProperty(""+r["Houseno"],r["ResidentId"])))))));
【解决方案2】:

您可以通过将DataTable 转换为Dictionary&lt;string, string []&gt; 然后使用支持将字典格式化为JSON 对象的JSON 序列化程序对其进行序列化,并将字典键映射到JSON 属性名称。 和 支持这个开箱即用;与 .Net 4.5 及更高版本中的 一样,如果您设置了 UseSimpleDictionaryFormat = true。

从数据表到字典的转换可以使用Linq如下完成,之后可以直接序列化字典:

// Choose the property name and value keys.
var propertyKey = "Block";
var valuesKey = "HouseNo";

// Generate the Dictionary<string, string []>
var dictionary = dataTable.AsEnumerable()
    // Generate a grouping of all houses for each block
    .GroupBy(r => r.Field<string>(propertyKey), r => r.Field<string>(valuesKey))
    // And convert to a dictionary of names and array values for JSON serialization.
    .ToDictionary(g => propertyKey + " " + g.Key, g => g.ToArray());

// Now serialize to JSON with your preferred serializer.  Mine is Json.NET
var json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);

生成以下 JSON:

{
  "Block A": [
    "101",
    "102",
    "103"
  ],
  "Block B": [
    "101",
    "102",
    "104"
  ]
}

注意事项:

  • 请务必使用命名空间 using System.Data; 并添加对 System.Data.DataSetExtensions.dll 的引用,因为我正在使用那里的一些扩展方法。

  • 我不知道有任何 JSON 序列化程序将 GroupBy() 返回的 IEnumerable&lt;IGrouping&lt;TKey, TElement&gt;&gt; 格式化为 JSON 对象,组键映射到属性名称,这就是为什么需要从中间分组表示。

工作示例.Net fiddle。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 2011-05-20
    • 2011-09-28
    相关资源
    最近更新 更多