【问题标题】:How to create a json object with repeating column value如何创建具有重复列值的 json 对象
【发布时间】:2017-11-30 10:34:12
【问题描述】:

这是我的查询输出:

        Month   SARType Count
        ---------------------------
        April   Data Protection Breach  2
        April   Miscellaneous - Employee Matters/Fraud  1
        April   Miscellaneous - Information Security    2
        April   Miscellaneous - Unusual Calls/Correspondence    1
        April   Theft - Damage/Theft/Lost Company Property  1
        March   Code of Conduct - Disclosure of Password    1
        March   Data Protection Breach  2
        March   Information Security - Phishing/Spear Phishing  1
        March   Miscellaneous - Employee Matters/Fraud  2
        March   Miscellaneous - Information Security    10
        March   Miscellaneous - Unusual Calls/Correspondence    5

我需要为 amcharts 创建一个以下样式的 json:

var chartData = [{
    month: "April",
    Data Protection Breach: 2,
    Miscellaneous - Employee Matters/Fraud: 1,
    Miscellaneous - Information Security: 2,
    Miscellaneous - Unusual Calls/Correspondence: 1},
   {
    month: "March",
    Data Protection Breach: 2,
    Miscellaneous - Employee Matters/Fraud: 1,
    Miscellaneous - Information Security: 2,
    Miscellaneous - Unusual Calls/Correspondence: 1}];

我不知道如何从查询结果中排除重复的月份列,并继续将相应的行作为参数添加到同一个 json 对象中。我正在使用字符串生成器在我的 MVC 应用程序中创建一个 json。任何帮助都将不胜感激!

【问题讨论】:

  • Month 分组,然后从组内的行创建字典/名称-值对
  • 我已经在我的查询中进行了分组,如何在代码中进行呢?
  • 有了LINQ Expression,你可以使用groupby
  • 显示您使用的是哪种数据类型DataTable 或集合?
  • @Fabio 我使用 DataTable 作为函数的输入。在那里,我使用 StringBuilder 来迭代表并创建一个 JSON,并将其传递回我的图表方法。

标签: c# json model-view-controller asp.net-mvc-5


【解决方案1】:

使用下面的代码,您应该获得每个月的字典集合,其中每个字典的键为 SARType 的值,值作为 Count 的值

var data = 
    yourDataTable.AsEnumerable()
                 .GroupBy(row => row.Field<string>("Month"))
                 .Select(group => 
                 {
                     var temp = new Dictionary<string, object>
                     {
                         { "month", group.Key }
                     }

                     foreach(var row in group)
                     {
                         temp.Add(row.Field<string>("SARType"), row.Field<int>("Count"));
                     }

                     return temp;
                 });

serializedData = Newtonsoft.Json.JsonConvert.SerializeObject(data);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    相关资源
    最近更新 更多