格式化 JSON 以显示高图表的格式

Formatting JSON for highchart

本文关键字:格式 高图表 显示 JSON 格式化      更新时间:2023-09-26

我正在运行一个servlet,它从doGet上的DB中提取数据,并使用JSON格式的字符串进行响应以填充Highchart.js时间序列图表:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String json = "";
        String sDate = request.getParameter("start");
        String eDate = request.getParameter("end");
        String app = request.getParameter("app");
        String env = request.getParameter("env");

            if (sDate != null && eDate != null) {
                Timestamp from = TimestampUtils.parseTimestamp(sDate, null);
                Timestamp to = TimestampUtils.parseTimestamp(eDate, null);
                try {
                    throughPutList = interop.getThroughputEntriesInTimespan(env, app, from, to);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                int counter = 1;
                if (throughPutList != null) {
                    json += "[";
                }
                assert throughPutList != null;
                for (ThroughputEntry chartModel : throughPutList) {
                    json += "[" + (chartModel.getRetrieved().getEpochSecond()* TimestampUtils.MILLIS_PER_SECOND + "," + chartModel.getThroughput() +  "]");
                    if (counter < throughPutList.size()) {
                        json += ",";
                    }
                    counter++;
                }
                if (throughPutList != null) {
                    json += "]";
                }
                if (throughPutList == null) {
                    json = "No record found";
                }
            } else {
                json = "Date must be selected." + "App : " + app + " " + eDate;
            }
            response.getWriter().write(json);
        }
}

我是javascripthighchartJSON的新手,是否可以对其进行优化以使用实际的JSON对象/数组而不是字符串,或者我有合理的方法来解决这个问题。

手动构造一个 JSON 字符串,这冒着结果字符串中出现语法错误的风险。由于您只是生成数字数组的数组,因此此风险似乎是可控的。否则,您可能希望使用所有常见 JSON 库提供的JSONWriter之类的东西。

一个小的性能改进是对可变json使用StringBuilder而不是String

我会改进错误处理。如果找不到数据或缺少参数,您将返回错误消息。

在第一种情况下,我只返回空数组,让客户端确定数据是空的。

如果缺少必需的参数,我会回答HTTP错误400(错误请求):

response.sendError(400);

如果在检索数据时发生运行时错误,我不会吞下异常,而是发送内部服务器错误 (500) 并记录异常。