Search code examples
c#asp.net-mvc-3google-visualization

Serialize List<T> into google charts json datatable


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

Solution

  • 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.