使用ajax从json动态生成json用于highcharts堆映射图

时间:2017-07-13 03:02:42

标签: highcharts

我的数据表(c#)中有数据,我打算将数据发送到JS,以便highcharts热图可以理解并绘制热图。

以下是数据表(c#)

的结构
xaxis yaxis value color
0       0    50   green
0       1    60   yellow
1       0    66   red
1       1    60   yellow 

我希望json采用以下格式,以便高图可以理解

[
{x:0,y:0,value:50,color:'green'},
{x:0,y:1,value:60,color:'yelow'},
{x:1,y:0,value:66,color:'red'},
{x:1,y:1,value:50,color:'green'}
]

请帮助我获得所需的输出。我得到所需的输出我将使用

设置到图表
chart.series[0].setdata(jsondata);

1 个答案:

答案 0 :(得分:1)

遗漏了代码和错误处理,但我认为这是你正在寻找的东西。

/// <summary>
/// serializable class that represent one data point
/// </summary>
[Serializable()]
class heatmap
{
    public int x { get; set; }
    public int y { get; set; }
    public int value { get; set; }
    public string color { get; set; }

    /// <summary>
    /// Use a public static function to copy data from the data table 
    /// to the list object
    /// </summary>
    /// <param name="table"></param>
    /// <returns></returns>
    public static List<heatmap> createHeatMap(ref DataTable table)
    {
        List<heatmap> list = new List<heatmap>();
        foreach(DataRow row in table.Rows)
        {
            heatmap map = new heatmap();
            map.x = Convert.ToInt32(row["x"]);
            map.y = Convert.ToInt32(row["y"]);
            map.value = Convert.ToInt32(row["value"]);
            map.color = Convert.ToString(row["color"]);
            list.Add(map);

        }

        return list;
    }

}

// your code that populates the datatable
//blah blah blah

List<heatmap> map = heatmap.createHeatMap(ref datatable);
// I use newtonsoft for serialization
string jsonMap = Newtonsoft.Json.JsonConvert.SerializeObject(map);
return jsonMap;