c# - 将 List<T> 序列化为 google charts json 数据表

标签 c# asp.net-mvc-3 google-visualization

我正在寻找一种将对象列表序列化为 google charts json 数据格式的通用方法。

This示例非常接近,但它使用的是数据表..

我希望这会涉及到一些反射(reflection)和模型属性的一些可能属性。 谁能告诉我图书馆之类的?

如果我可以将这样的查询序列化为 google 图表格式,那就更好了:

var results = from m in be.cmsMember
      where m.FirstLogin != null
      && m.FirstLogin >= BitCoinGoLive
      group m by

      new { Year = m.FirstLogin.Value.Year, Month = m.FirstLogin.Value.Month, Day =           m.FirstLogin.Value.Day } into grp
      select new
      {
                              Year = grp.Key.Year,
                              Month = grp.Key.Month,
                              Day = grp.Key.Day,
                              Count = grp.Count()
      };

最佳答案

我会创建自己的类层次结构来匹配 Google 的 API,然后使用 JSON.NET 对其进行序列化。可能的数据模型:

public class Graph {
    public ColInfo[] cols { get; set; }
    public DataPointSet[] rows { get; set; }
    public Dictionary<string, string> p { get; set; }
}

public class ColInfo {
    public string id { get; set; }
    public string label { get; set; }
    public string type { get; set; }
}

public class DataPointSet {
    public DataPoint[] c { get; set; }
}

public class DataPoint {
    public string v { get; set; } // value
    public string f { get; set; } // format
}

然后是一个示例用法:

var graph = new Graph {
    cols = new ColInfo[] {
        new ColInfo { id = "A", label = "set A", type = "string" },
        new ColInfo { id = "B", label = "set B", type = "string" },
        new ColInfo { id = "C", label = "set C", type = "string" }
    },
    rows = new DataPointSet[] {
        new DataPointSet {
            c = new DataPoint[] {
                new DataPoint { v = "a" },
                new DataPoint { v = "b", f = "One" }
            }
        }
    },
    p = new Dictionary<string, string>()
};

string json;
//var s = new JsonSerializer();
var s = new JavaScriptSerializer();
/*using (var sw = new StringWriter()) {
    s.Serialize(sw, graph);
    json = sw.ToString();
}*/
var sw = new StringBuilder();
s.Serialize(graph, sw);
json = sw.ToString();

您可以使用 Linq 的 Select() 将您的数据转换为 Google 的数据模型,然后将其序列化为 JSON。

关于c# - 将 List<T> 序列化为 google charts json 数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6149203/

相关文章:

c# - 始终以管理员身份运行使用 Windows 桌面桥转换的应用程序?

c# - 位于 "address"的 HTTP 服务太忙

javascript - 如何将另一个数据系列添加到 Google 图表

javascript - 谷歌折线图上的额外直线

javascript - 如何标记 Google 柱形图条

c# - 迭代器中的副作用被认为是有害的?

c# - HTMLAgilityPack QuerySelectorAll 抛出异常,可能 Fizzler dll 版本不匹配?

asp.net-mvc - MVC3 将@model 传递给局部 View

c# - 在 Controller 的构造函数之外使用依赖注入(inject)

entity-framework - 保存时忽略可选列