有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java解析JSON以在highchart中使用。js

我从数据库中提取多个值,并在servlet中对它们进行计算,然后将这些值作为响应传递回我的前端,然后前端使用highchart.js来可视化数据

目前,我正在创建一个JSON对象形式的字符串,highchart可以使用它,但我想通过使用像GSON或Jackson这样的库来完善我的代码 显然,这将不太容易出错,并且更易于重用,但我不确定我是否能够做到这一点

我当前的解析方法:

        this.json = "[";
        this.zoneId = ZoneId.of("Europe/Dublin");
        this.map = new LinkedHashMap<>();
        this.dayCount = 0;
        this.end = "[" + (to.toInstant().getEpochSecond() * TimestampUtils.MILLIS_PER_SECOND + "," + null + "]]}");

public String Generate(String type) {

    // Check that we have dates to work with
    if (sDate != null && eDate != null) {

        // Pull data from DB
        try {
            throughPutList = dbWork.getThroughputEntriesInTimespan(env, app, from, to, connection);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String[] calculations = new String[]{"default", "total"};

        assert throughPutList != null;
        int count = 1;
        for (String calc : calculations) {
            for (ThroughputEntry chartModel : throughPutList) {

                // Convert the epochSecond value of the period pulled for the DB to it's day for insertion into a Map
                ZonedDateTime zdt = ZonedDateTime.ofInstant(chartModel.getRetrieved(), zoneId);
                LocalDate localDate = zdt.toLocalDate();
                entryDay = localDate.atStartOfDay(zoneId).toEpochSecond() * TimestampUtils.MILLIS_PER_SECOND;
                valueForDate = map.get(entryDay);

                if (count == 1) {
                    json += "{\"name\": \"" + calc + "\", \"data\":[[" + (from.toInstant().getEpochSecond() * TimestampUtils.MILLIS_PER_SECOND + "," + null + "],");
                }
                if (calc.equals("default")) {
                    Default(chartModel);
                } else if (calc.equals("total")) {
                    Total(chartModel);
                } 
                if (count == throughPutList.size()) {

                    for (Map.Entry<Long, BigDecimal> entry : map.entrySet()) {

                        json += "[" + (entry.getKey() + "," + entry.getValue() + "],");
                    }
                    if (calc != "total") {
                            json += end + ",";

                    } else {
                            json += end;
                    }

                    map.clear();
                    count = 0;
                }
                count++;
            }
        }
        json += "]";

        if (throughPutList == null) {
            json = "No record found";
        }
    } else {
        json = "Date must be selected." + "App : " + app + " " + eDate;
    }
    return json;
}

public void Default(ThroughputEntry chartModel) {

    map.put(chartModel.getRetrieved().getEpochSecond() * TimestampUtils.MILLIS_PER_SECOND, BigDecimal.valueOf(chartModel.getThroughput()));
}

public void Total(ThroughputEntry chartModel) {

    newTotalForDate = (null == valueForDate) ? BigDecimal.valueOf(chartModel.getThroughput()) :
            valueForDate.add(BigDecimal.valueOf(chartModel.getThroughput()));

    if (null == newTotalForDate) {  // If we failed to get new value.
        // TODO: Handle error condition.
    } else {  // Else normal, we have a new total. Store it in map.

        map.put(entryDay, newTotalForDate);  // Replaces any old value.s
    }
}

因此,库需要使用String值和linkedHashMap来填充JSON响应

响应JSON需要采用以下形式:

[{"name": "mean", "data":[[1454806080000,null],[1454889600000,204.043],[1454976000000,202.281],[1455062400000,160.493],[1455148800000,206.000],[1455235200000,229.917],[1455321600000,82.430],[1455408000000,87.242],[1455494400000,223.584],[1455580800000,188.412],[1455667200000,228.199],[1455753600000,224.268],[1455840000000,198.513],[1455842880000,null]]},{"name": "extrapo", "data":[[1454806080000,null],[1455842880000,null]]},{"name": "max", "data":[[1454806080000,null],[1455842880000,null]]}]

实践中的响应将包含更多的数据集

我正在消费这个客户端:

// Function for loading data via AJAX and showing it on the chart
function ajaxLoadChart(startDate, endDate, appName, envName) {
    // If no data is passed (the chart was cleared)
    if (!startDate || !endDate) {
        return;
    }
    // Otherwise, issue an AJAX request
    $.ajax({
        url: 'http://myServlet.com/operations.PreProcessor',
        crossDomain: true,
        async: true,
        type: "GET",
        dataType: "json",
        data: {
            start: startDate,
            end: endDate,
            env: envName,
            app: appName
        },
        success: function (json) {

            options.series[0] = json[0];
            options.series[1] = json[1];
            options.series[2] = json[2];
            chart = new Highcharts.Chart(options); 
        },
        error: function (xhr, status, error) {
            alert(status + " " + error);
            console.log(xhr);
        }
    })
}

是否可以使用上述库之一来实现这一点


共 (1) 个答案

  1. # 1 楼答案

    我想我理解你想要实现的目标,我自己也做过类似的事情

    要做的事情是创建一些pojo(纯Ol'javaoblect),它们表示您当前在JSON中创建的数据结构。它们应该具有与当前JSON结构相同的成员名、子级等。然后构建它,然后将其传递给GSON以序列化为JSON

    我已经这样做了,并调用了我创建的“视图模型”对象,然后将其作为JSON字符串传递给客户端