我从数据库中提取多个值并在servlet中对它们进行计算,并将值作为响应传递回我的前端,然后使用highchart.js
来显示数据。
目前我以高图可以使用的JSON对象的形式创建一个字符串,但我想通过使用像GSON或Jackson这样的libaray来优化我的代码 显然,这将更容易出错并且更容易重复使用,但我不确定我是否能够做到这一点。
我目前的解析方法:
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需要具有以下形式:
[{"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]]}]
实践中的反应将有更多的数据~126套。
我正在消费这个客户方:
// 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);
}
})
}
是否可以使用其中一个提到的库来实现这一目标?
答案 0 :(得分:0)
我想我明白你想要实现的目标并且自己做了类似的事情。
要做的是创建一些POJOS(Plain Ol'Java Oblects),它代表您当前在JSON中创建的数据结构。这些应该具有与当前JSON结构相同的成员名称,子项等。然后构建它然后将其传递给GSON以序列化为JSON。
我已经完成了这个并调用了我创建的“View Model”对象,然后将其作为JSON字符串传递给客户端。