Gson使用Highcharts获取饼图的Json值

时间:2022-12-03 17:47:48

I am working on Pie Charts using HighCharts.

我正在使用HighCharts处理Pie Charts。

The structure of JSON i needed is

我需要的JSON结构是

 data: [
            ['Firefox',   45.0],
            ['IE',       26.8],                
            ['Safari',    8.5],
            ['Opera',     6.2],
            ['Others',   0.7]
        ]

I am using GSON to convert this into JSON object.

我正在使用GSON将其转换为JSON对象。

I tried to add a class 'Browser' which contains

我试图添加一个包含的“浏览器”类

 private List browserName = new ArrayList();
 private List browserValue = new ArrayList();

// passing the browser class object to Gson
   gson.toJson(browser);

In graph I passed the data as

在图中,我将数据作为

 data: [
               json.browserName,json.browserValue

        ]

But this didnt worked. How can I achieve the required JSON format when name and value is a list.

但这并没有奏效。当名称和值是列表时,如何实现所需的JSON格式。

1 个解决方案

#1


I added some quotes and braces to make your json valid. Then, it's a matter of looping through your data key which gives you an array of arrays.

我添加了一些引号和括号,以使您的json有效。然后,这是循环数据键的问题,它为您提供了一组数组。

String jsonString = 
    "{'data':[['Firefox',45.0],['IE',26.8],['Safari',8.5],['Opera',6.2],['Others',0.7]]}";
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject();
JsonArray data = jsonObject.get("data").getAsJsonArray();
for(int i = 0; i < data.size(); i++) {
    JsonArray dataIndex = data.get(i).getAsJsonArray();
    System.out.println(dataIndex.get(0));
    System.out.println(dataIndex.get(1));
}

I find it helps me to visualize the json before writing code to go in and get values.

我发现在编写代码之前可视化json有助于我进入并获取值。

#1


I added some quotes and braces to make your json valid. Then, it's a matter of looping through your data key which gives you an array of arrays.

我添加了一些引号和括号,以使您的json有效。然后,这是循环数据键的问题,它为您提供了一组数组。

String jsonString = 
    "{'data':[['Firefox',45.0],['IE',26.8],['Safari',8.5],['Opera',6.2],['Others',0.7]]}";
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject();
JsonArray data = jsonObject.get("data").getAsJsonArray();
for(int i = 0; i < data.size(); i++) {
    JsonArray dataIndex = data.get(i).getAsJsonArray();
    System.out.println(dataIndex.get(0));
    System.out.println(dataIndex.get(1));
}

I find it helps me to visualize the json before writing code to go in and get values.

我发现在编写代码之前可视化json有助于我进入并获取值。