【问题标题】:How to change the format of a dictionary?如何更改字典的格式?
【发布时间】:2015-01-30 12:08:41
【问题描述】:

在 MVC JsonResult 操作中,我将数据绑定到字典并通过 JSON 返回。它以不同于我需要的形式为我提供数据。

我的代码:

var query = obj.Where(x => x.Date > new DateTime(01 / 01 / 2000)
                        && x.Date <= Convert.ToDateTime(shortDate))
               .GroupBy(x => x.Date)
               .Select(x => new { LogDate = x.Key, Count = x.Count() });

Dictionary<string, int> openWith =  new Dictionary<string, int>();
foreach (var output in query)
{
   openWith.Add(output.LogDate.ToShortDateString(), output.Count);
}
string letter = "letter";
var chartsdata = openWith;
return Json(chartsdata,letter, JsonRequestBehavior.AllowGet);

JSON 数据的格式为:

var data1 = {
    "01/28/2015": 1,
    "01/30/2015": 6, 
    "01/29/2015": 1, 
    "01/22/2015": 3, 
    "01/20/2015": 1, 
    "01/10/2015": 5 }

要绘制图表,我需要表格中的数据:

var data1 = [
    [gd(2015, 1, 28), 1],
    [gd(2015, 1, 30), 6],
    [gd(2015, 1, 29), 1],
    [gd(2015, 1, 22), 3],
    [gd(2015, 1, 20), 1],
    [gd(2015, 1, 10), 5] ]

如果有人知道,请告诉我:如何更改数据格式?

【问题讨论】:

    标签: c# json dictionary flot


    【解决方案1】:

    试试这个。

    foreach (var output in query)
    {
        openWith.Add("gd(" + output.LogDate.Year + ", " +  output.LogDate.Month + ", "
        + output.LogDate.Day + ")", output.Count);
    }
    

    【讨论】:

    • 尝试使用字符串格式而不是使用+来分隔字符串。
    • 现在数据将是[["gd(2015, 1, 28)", 1]...] 而不是[[gd(2015, 1, 28), 1]...]
    • 感谢您的帮助...但返回如下:{"gd(2015, 1, 28)":1,"gd(2015, 1, 30)":6}
    【解决方案2】:

    使用

    foreach (var output in query)
    {
        openWith.Add(output.LogDate.Subtract(new DateTime(1970,1,1)).TotalMilliseconds, output.Count);
    }
    

    这样,您可以在服务器端计算时间戳,而无需调用gd 函数。

    【讨论】:

    • 它显示错误:有一些无效的参数,因为字符串格式的字典键
    • @sandeepsingh 您必须将openWith 更改为Dictionary&lt;double, int&gt;,因为现在使用double 而不是string
    【解决方案3】:

    根据JSON standard,您返回的字符串不是有效的 JSON。表达式 gd(2015, 1, 28) 不是有效的 JSON 原语之一,它们是 "string"(引号)、numbertruefalsenull。据我所知,没有任何内置的 .Net JSON 格式化程序会生成类似这样的 JSON。

    因此,您需要自己手动构造一个包含所需表达式的字符串,然后将其返回:

            var jsonString = query.Aggregate(new StringBuilder("["), (sb, pair) =>
            {
                if (sb.Length > 1)
                    sb.AppendLine(",");
                return sb.AppendFormat("[gd({0}, {1}, {2}), {3}]", pair.LogDate.Year, pair.LogDate.Month, pair.LogDate.Day, pair.Count);
            }).Append("]").ToString();
    
            Debug.WriteLine(jsonString);
    

    产生:

    [[gd(2015, 1, 28), 1],
    [gd(2015, 1, 30), 6],
    [gd(2015, 1, 29), 1],
    [gd(2015, 1, 22), 3],
    [gd(2015, 1, 20), 1],
    [gd(2015, 1, 10), 5]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      相关资源
      最近更新 更多