String response = null; Dict dict = null; try response = HttpUtilcreateGetgeometryUrlformgisDtoexecutebody; dict = JSONparseObjectresponse Dictclass; catch
-
使用try-with-resources来关闭资源,避免资源泄漏
-
将JSON解析和数据处理分离,提高代码的可读性和可维护性
-
使用Lambda表达式简化循环遍历操作,提高代码的简洁性和可读性
-
使用Java 8的Stream API来进行数据处理,进一步简化代码
-
将方法签名中的Exception去掉,避免向上抛出不必要的异常
-
将日志记录从错误级别改为调试级别,避免在生产环境中记录过多无用的错误日志
优化后的代码如下所示:
public JSONArray getGeometryData(String geometryUrl, GisDto gisDto) {
try (CloseableHttpResponse response = HttpUtil.createGet(geometryUrl).form(gisDto).execute()) {
String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
Dict dict = JSON.parseObject(responseBody, Dict.class);
JSONArray jsonArray = dict.getJSONArray("data");
return jsonArray.stream()
.map(obj -> (JSONObject) obj)
.peek(jsonObject -> {
JSONObject geometry = jsonObject.getJSONObject("geometry");
JSONArray pointsArray = geometry.getJSONArray("points");
JSONArray innerArray = new JSONArray();
pointsArray.forEach(obj -> {
JSONArray innerPointsArray = (JSONArray) obj;
JSONArray pointArray = new JSONArray();
innerPointsArray.forEach(innerObj -> {
JSONObject pointObj = (JSONObject) innerObj;
double x = pointObj.getDouble("x");
double y = pointObj.getDouble("y");
JSONArray innerPointArray = new JSONArray();
innerPointArray.add(x);
innerPointArray.add(y);
pointArray.add(innerPointArray);
});
innerArray.add(pointArray);
});
geometry.put("points", innerArray);
})
.collect(Collectors.toCollection(JSONArray::new));
} catch (IOException e) {
log.debug(e.getMessage());
return new JSONArray();
}
}
``
原文地址: https://www.cveoy.top/t/topic/fvnw 著作权归作者所有。请勿转载和采集!