我正在寻找一种将对象列表序列化为 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/