序列化列表进入谷歌图表 json 数据表

发布于 2024-11-09 21:35:06 字数 784 浏览 3 评论 0原文

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

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

我希望这会涉及一些反射以及模型属性上的一些属性。 谁能指点我去图书馆之类的地方吗?

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

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()
      };

I'm looking for a generic way of serializing a List of objects into the google charts json data format.

This example is quite close, but it's using a datatable..

I expect this would involve some reflection and some maybe attrbutes on the model properties.
Can anyone point me to a library or something?

Even better would be if I could serialize a query like this into the google charts format:

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()
      };

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

沫离伤花 2024-11-16 21:35:06

我将创建自己的与 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。

I would create my own class hierarchy that matches Google's API and then use JSON.NET to serialize it. The possible data model:

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
}

Then an example usage:

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();

You can use Linq's Select() to transform your data into Google's data model, then serialize it to JSON.

樱花坊 2024-11-16 21:35:06

这是一个完整的工作函数,也适用于匿名类型。

但要小心日期:这些也需要在客户端上解析:例如

for (var i = 0; i < data.rows.length;i++ ) {
   data.rows[i].c[0].v = new Date(data.rows[i].c[0].v);
}



private string getGetJsonString<T>(IEnumerable<dynamic> list, dynamic row) {

    string header = "{\"cols\":[";
    PropertyInfo[] props = row.GetType().GetProperties();
    foreach (PropertyInfo p in props)
    {

        header += "{\"id\":\"" + p.Name + "\", \"label\":\"" + p.Name + "\",";
        switch (p.PropertyType.Name)
        {
            case "Int32":
                header += "\"type\":\"number\"";
                break;
            case "DateTime":
                header += "\"type\":\"date\"";
                break;
            default:
                header += "\"type\":\"string\"";
                break;
        }
        header += "},";
    }
    header = header.Substring(0, header.Length - 1);
    header += "]";

    StringBuilder json = new StringBuilder();
    json.Append(header + ",\"rows\":[");

    bool first = true;
    foreach (dynamic a in list)
    {
        string jRow = "{\"c\":[";
        if (first)
            first = false;                    
        else
            jRow = "," + jRow;

        foreach (PropertyInfo p in props)
        {

            // todo get other fieldtypes from http://code.google.com/apis/chart/interactive/docs/reference.html#dataparam
            switch (p.PropertyType.Name)
            {
                case "Int32":
                    jRow += "{\"v\":";
                    jRow += p.GetValue(a,null).ToString();
                    jRow += "},";
                    break;
                case "DateTime":
                    jRow += "{\"v\":\"";
                    DateTime d = ((DateTime)p.GetValue(a, null));
                    //jRow += d.DayOfYear;
                    //jRow += "\\/Date("+d.Ticks+")\\/";
                    jRow += d.ToString("yyyy-MM-dd");
                    //jRow += "new Date(" + d.Ticks+ ")";
                    jRow += "\"},";
                    break; 
                default:
                    jRow += "{\"v\":\"";
                    jRow += p.GetValue(a,null).ToString();
                    jRow += "\"},";
                    break;
            }

        }
        jRow = jRow.Substring(0, jRow.Length - 1);
        json.Append(jRow + "]}");
    }

    json.Append("]}");


    return json.ToString() ;
}

Here's a full working funciton which also works with anonymous types.

Carefull with dates though: these need to parsed on the client as well:e.g.

for (var i = 0; i < data.rows.length;i++ ) {
   data.rows[i].c[0].v = new Date(data.rows[i].c[0].v);
}



private string getGetJsonString<T>(IEnumerable<dynamic> list, dynamic row) {

    string header = "{\"cols\":[";
    PropertyInfo[] props = row.GetType().GetProperties();
    foreach (PropertyInfo p in props)
    {

        header += "{\"id\":\"" + p.Name + "\", \"label\":\"" + p.Name + "\",";
        switch (p.PropertyType.Name)
        {
            case "Int32":
                header += "\"type\":\"number\"";
                break;
            case "DateTime":
                header += "\"type\":\"date\"";
                break;
            default:
                header += "\"type\":\"string\"";
                break;
        }
        header += "},";
    }
    header = header.Substring(0, header.Length - 1);
    header += "]";

    StringBuilder json = new StringBuilder();
    json.Append(header + ",\"rows\":[");

    bool first = true;
    foreach (dynamic a in list)
    {
        string jRow = "{\"c\":[";
        if (first)
            first = false;                    
        else
            jRow = "," + jRow;

        foreach (PropertyInfo p in props)
        {

            // todo get other fieldtypes from http://code.google.com/apis/chart/interactive/docs/reference.html#dataparam
            switch (p.PropertyType.Name)
            {
                case "Int32":
                    jRow += "{\"v\":";
                    jRow += p.GetValue(a,null).ToString();
                    jRow += "},";
                    break;
                case "DateTime":
                    jRow += "{\"v\":\"";
                    DateTime d = ((DateTime)p.GetValue(a, null));
                    //jRow += d.DayOfYear;
                    //jRow += "\\/Date("+d.Ticks+")\\/";
                    jRow += d.ToString("yyyy-MM-dd");
                    //jRow += "new Date(" + d.Ticks+ ")";
                    jRow += "\"},";
                    break; 
                default:
                    jRow += "{\"v\":\"";
                    jRow += p.GetValue(a,null).ToString();
                    jRow += "\"},";
                    break;
            }

        }
        jRow = jRow.Substring(0, jRow.Length - 1);
        json.Append(jRow + "]}");
    }

    json.Append("]}");


    return json.ToString() ;
}
郁金香雨 2024-11-16 21:35:06

查看 JSON.NET。这是一个很棒的库,可以根据您的类生成 json,此页面将为您提供如何序列化的示例: http://james.newtonking.com/pages/json-net.aspx

希望这能为您指明正确的方向,

Have a look at JSON.NET. It's a great library to generate json based on your class, this page will give you examples of how to serialise : http://james.newtonking.com/pages/json-net.aspx.

Hopefully this will point you in the right direction,

乖乖 2024-11-16 21:35:06

我建议使用与 google 图表 JSON 格式相匹配的类组合,并结合 Json.net。基本步骤是。

  1. 指定列
  2. 从任何来源(使用 linq)选择数据到与正确的列相匹配的行单元格值,
  3. 并使用 JSON.net 序列化为 json

这是 @emfurry 和 @TWith2Sugars 的两个建议的组合。

因此,使用类似于@emfurrys的类(也许添加一些构造函数来消除对对象初始化程序的需要)有点像:

Table table = new Table();

ColInfo[] cols = new ColInfo[4]; 
cols.Add("year", "Year", "string");
cols.Add("month", "Month", "string");  
cols.Add("day", "Day", "string"); 
cols.Add("count", "Count", "number"); 

table.rows = cmsMembersWithCount.Select(row => new DataPointSet(){ 
{new DataPoint(row.Year)} 
{new DataPoint(row.Month)} 
{new DataPoint(row.Day)} 
{new DataPoint(row.Count)} 
}).ToArray();


var json = JsonConvert.SerializeObject(table);

bob是你的叔叔。注意 Bob 未经测试,他在这里只是作为一个小例子,他做了一些假设,但他希望给出如何快速从任何数据源到 Google 图表 JSON 格式的概述。

I recommend using a combination of classes matching google's JSON format for the charts, combined with Json.net. Essential steps are.

  1. Specify your columns
  2. Select your data from whatever source (using linq) into row cell values matching the correct columns
  3. serialise out to json with JSON.net

This is a combination of the two suggestions by @emfurry and @TWith2Sugars.

So with classes similar to @emfurrys in place (maybe add some constructors to remove need for object initialiser) Something a bit like :

Table table = new Table();

ColInfo[] cols = new ColInfo[4]; 
cols.Add("year", "Year", "string");
cols.Add("month", "Month", "string");  
cols.Add("day", "Day", "string"); 
cols.Add("count", "Count", "number"); 

table.rows = cmsMembersWithCount.Select(row => new DataPointSet(){ 
{new DataPoint(row.Year)} 
{new DataPoint(row.Month)} 
{new DataPoint(row.Day)} 
{new DataPoint(row.Count)} 
}).ToArray();


var json = JsonConvert.SerializeObject(table);

bob's your uncle. N.B Bob is untested, he's here just as a little example, he assumes a fair bit, but he hopefully gives the outline of how to go quickly from any data source to Google's chart JSON format.

我喜欢麦丽素 2024-11-16 21:35:06

我使用 Google DataTable .Net Wrapper,可在 Nuget。我的博客中有一篇关于它的小文章 http://nicholasbering.ca/dot-net/2014/10/24/google-data-table-dot-net-wrapper/,但总而言之,你可以做类似的事情 下列的。

var list = new[]
                 {
                     new {Name = "Dogs", Count = 5},
                     new {Name = "Cats", Count = 2}
                 };

 var json = list.ToGoogleDataTable()
                .NewColumn(new Column(ColumnType.String, "Name"), x => x.Name)
                .NewColumn(new Column(ColumnType.Number, "Count"), x => x.Count)
                .Build()
                .GetJson();

上面的示例适用于数组,但它应该适用于任何 IEnumrable

I use Google DataTable .Net Wrapper, available on Nuget. I have a little article about it in my blog at http://nicholasbering.ca/dot-net/2014/10/24/google-data-table-dot-net-wrapper/, but to sum it up you could do something like the following.

var list = new[]
                 {
                     new {Name = "Dogs", Count = 5},
                     new {Name = "Cats", Count = 2}
                 };

 var json = list.ToGoogleDataTable()
                .NewColumn(new Column(ColumnType.String, "Name"), x => x.Name)
                .NewColumn(new Column(ColumnType.Number, "Count"), x => x.Count)
                .Build()
                .GetJson();

The example above is working on an array, but it should work on any IEnumrable<T>.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文