如何从C#为Google图表格式化JSON

本文关键字:表格 格式化 JSON Google | 更新日期: 2023-09-27 18:00:15

我正在尝试从c#输出JSON,以便与谷歌图表一起使用。

目前我使用JSON.Net构建它:

  JArray arrB =     new JArray(
                        from c in cards
                        where c.complete
                               group c by new { date = Convert.ToDateTime(c.completed).Date } into g
                               select new JObject(
                                   new JProperty("date", g.Key.date),
                                   new JProperty("completedHours", g.Sum(x => x.estHours))
                                   ) 
                        );

输出以下内容:

 { "burndown" : [ { "completedHours" : 30.0,
[ { "completedHours" : 30.0,
    "date" : "2014-03-26T00:00:00+00:00"
  },
  { "completedHours" : 3.0,
    "date" : "2014-04-03T00:00:00+01:00"
  },
  { "completedHours" : 3.0,
    "date" : "2014-03-28T00:00:00+00:00"
  },
  { "completedHours" : 1.0,
    "date" : "2014-03-27T00:00:00+00:00"
  }
]

然而,谷歌图表不喜欢这样。就我所能计算出的而言,我需要对它进行格式化,使它在第一个数据块中有列标题,然后是后面的内容。我是JSON的新手,所以不知道该怎么做。

编辑:添加"正确"结构

据我从谷歌图表文档中所知,正确的格式应该是这样的:

{"cols":[{"id":"Col1","label":"","type":"date"}],
  "rows":[
    {"c":[{"v":"a"},{"v":"Date(2010,10,6)"}]},
    {"c":[{"v":"b"},{"v":"Date(2010,10,7)"}]}
  ]
} 

请参阅:https://developers.google.com/chart/interactive/docs/reference#dataparam

如何从C#为Google图表格式化JSON

根据您的JSON模式,您的对象层次结构需要如下所示:

public class Col
{
    public string id { get; set; }
    public string label { get; set; }
    public string type { get; set; }
}
public class C
{
    public string v { get; set; }
}
public class Row
{
    public List<C> c { get; set; }
}
public class RootObject
{
    public List<Col> cols { get; set; }
    public List<Row> rows { get; set; }
}

因此,要构建json,您需要执行以下操作:

var rootObject = new RootObject()
{
    cols = new List<Col>
    {
        new Col {id = "1", label = "2", type = "string"}
    },
    rows = new List<Row>()
    {
        new Row 
        {
           c = new List<C> { 
               new C { v = "a" },
               new C { v = "b"}
           }
        }
    }
};