使用jQuery for Highcharts迭代JSON响应

时间:2011-03-25 12:50:41

标签: javascript jquery json servlets highcharts

我创建了一个创建Map对象的servlet:

Map<String, Integer> data = new LinkedHashMap<String, Integer>();

使用google JSON填写数据并以JSON格式返回响应:

String json = new Gson().toJson(data);

检索数据并将其迭代到表中时,所有这些都可以正常工作。但我需要特殊格式的Highcharts插件:

series: [{
    name: 'Monday',
     data: [10]
    }, {
     name: 'Tuesday',
     data: [20]
  }, {
     name: 'Wednesday',
     data: [30]
    }, {
     name: 'Thursday',
     data: [40]          
    }, {
     name: 'Friday',
     data: [50]
    }, {
     name: 'Saturday',
     data: [60]            
    }, {
     name: 'Sunday',
     data: [70]             
}]

为了实现这一目标,您必须创建如下所示的脚本:

$(document).ready(function() {
    var options = {
        chart: {
            renderTo: 'container',
            defaultSeriesType: 'column',
            rightMargin: 80
        },

        title: {
            text: 'Weekdays'
        },
        subtitle: {
            text: 'Source: somewhere in a calendar'
        },

         xAxis: {
            labels: {
                enabled: false
        }
        },

        yAxis: [
            {
                min: 0,
                title: {
                    text: 'Amount'
                 }
            },
            {
                linkedTo: 0,
                opposite: true
            }
        ],

         series: []
    };

    $.getJSON('WeekdayServlet', function(data) {

        var series = [];

        $.each(data, function(key, value) {

            series.name = key;
            series.data = value;

        options.series.push(data);
    });

    // Create the chart
    var chart = new Highcharts.Chart(options);

 }); 

无论如何,我在这里做错了。在迭代中或我如何“初始化”系列

以下是我更好理解的来源:

1 个答案:

答案 0 :(得分:3)

[]应映射到Java集合,例如List或数组。 {}应映射到Map或某些Javabean。

因此,可以按如下方式翻译/实现所需的JSON格式:

public class Serie {
    private String name;
    private Integer[] data;

    public Serie() {
        // Keep default c'tor alive.
    }

    public Serie(String name, Integer... data) {
        this.name = name;
        this.data = data;
    }

    // Add/generate getters/setters/etc.
}

List<Serie> series = new ArrayList<Serie>();
series.add(new Serie("Monday", 10));
series.add(new Serie("Tuesday", 20));
series.add(new Serie("Wednesday", 30));
// ...
Map<String, Object> data = new HashMap<String, Object>();
data.put("series", series);
// ...
String json = new Gson().toJson(data);
// ...