Repeat JSON response with jQuery for Highcharts

I made a servlet that creates a map object:

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

fills in the data and returns a response in JSON format using google JSON:

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

All this works great when retrieving data and repeating it into a table. But I need it in a special format for the Highcharts plugin:

 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] }] 

To do this, you need to create a script as shown below:

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

Anyway, I'm doing something wrong. Either in an iteration, or how to β€œinitialize” a series .

Here are my sources for a better understanding:

+1
source share
1 answer

[] must map to a Java collection, such as a List or an array. {} should appear in Map or some javabey.

Thus, the desired JSON format can be translated / achieved as follows:

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

and

 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); // ... 
+3
source

All Articles