如何更改字典的格式?

时间:2015-01-30 12:08:41

标签: c# json dictionary flot

在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] ]

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

3 个答案:

答案 0 :(得分:0)

试试这个。

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

答案 1 :(得分:0)

使用

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

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

答案 2 :(得分:0)

根据JSON standard,您返回的字符串无效JSON。表达式gd(2015, 1, 28)不是有效的JSON基元之一,"string"(在引号中),numbertruefalse和{{1} }。据我所知,内置的.Net JSON格式化程序都不会产生类似的JSON。

因此,您需要自己手动构造一个包含所需表达式的字符串,并按原样返回:

null

产生:

        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);
相关问题