while (!isLastPage) { // 封装请求头 ResponseEntity<String> responseEntity = restTemplate.exchange(StrUtil.format(djUrl, qssj, zzsj, page, limit), HttpMethod.GET, formEntity, String.class); JSONObject response = JSONUtil.parseObj(responseEntity.getBody()); log.info("调用登记信息查询接口返回:{}",responseEntity.getBody()); if (!"200".equals(response.getStr("code"))) { log.info("调用登记信息查询接口返回不是成功:{}_{}", response.get("code"), response.get("msg")); break; } List<BdBdcDj> djList = new ArrayList<>(); List<BdMessage> messageList = new ArrayList<>(); // 解析数据 JSONArray data = response.getJSONArray("data"); data.toList(JSONObject.class).forEach(jsonObject -> { String bsm = jsonObject.getStr("bsm"); // 如果数据库已存在本条记录,则忽略 if (bdBdcDjDao.selectByPrimaryKey(bsm) == null) { // 使用 MapperUtils.map 枚举字段设置有问题,勿改 BdBdcDj bdBdcDj = BeanUtil.mapToBean(jsonObject, BdBdcDj.class, false, null); bdBdcDj.setId(bsm); bdBdcDj.setHouseId(jsonObject.getStr("hbsm")); bdBdcDj.setDivisionCode(jsonObject.getStr("qxdm")); // 如果是转移登记则待处理 if ("C".equals(jsonObject.getStr("djlx"))) { bdBdcDj.setResolveStatus(ResolveStatusEnum.WAITING); // 如果是转移登记则如bdMessage,并推送维资 BdMessage msg = getMessageByDj(bdBdcDj); messageList.add(msg); } else { bdBdcDj.setResolveStatus(ResolveStatusEnum.NO_NEED); } djList.add(bdBdcDj); } });
时间: 2024-02-10 16:08:09 浏览: 143
Java纯手工分页代码PageUtil.rar
首先可以将代码分离成不同的方法,提高可读性和可维护性,比如解析数据的部分可以封装成一个方法:
```java
private List<BdBdcDj> parseData(JSONArray data) {
List<BdBdcDj> djList = new ArrayList<>();
data.toList(JSONObject.class).forEach(jsonObject -> {
String bsm = jsonObject.getStr("bsm");
// 如果数据库已存在本条记录,则忽略
if (bdBdcDjDao.selectByPrimaryKey(bsm) == null) {
// 使用 MapperUtils.map 枚举字段设置有问题,勿改
BdBdcDj bdBdcDj = BeanUtil.mapToBean(jsonObject, BdBdcDj.class, false, null);
bdBdcDj.setId(bsm);
bdBdcDj.setHouseId(jsonObject.getStr("hbsm"));
bdBdcDj.setDivisionCode(jsonObject.getStr("qxdm"));
// 如果是转移登记则待处理
if ("C".equals(jsonObject.getStr("djlx"))) {
bdBdcDj.setResolveStatus(ResolveStatusEnum.WAITING);
// 如果是转移登记则如bdMessage,并推送维资
BdMessage msg = getMessageByDj(bdBdcDj);
messageList.add(msg);
} else {
bdBdcDj.setResolveStatus(ResolveStatusEnum.NO_NEED);
}
djList.add(bdBdcDj);
}
});
return djList;
}
```
然后将`while`循环体中的代码进行重构,提高代码可读性,例如:
```java
do {
ResponseEntity<String> responseEntity = restTemplate.exchange(StrUtil.format(djUrl, qssj, zzsj, page, limit), HttpMethod.GET, formEntity, String.class);
JSONObject response = JSONUtil.parseObj(responseEntity.getBody());
log.info("调用登记信息查询接口返回:{}", responseEntity.getBody());
if (!"200".equals(response.getStr("code"))) {
log.info("调用登记信息查询接口返回不是成功:{}_{}", response.get("code"), response.get("msg"));
break;
}
JSONArray data = response.getJSONArray("data");
List<BdBdcDj> djList = parseData(data);
bdBdcDjDao.insertBatch(djList);
page++;
isLastPage = data.size() < limit;
} while (!isLastPage);
```
最后,可以将`BdMessage msg = getMessageByDj(bdBdcDj);`这段代码移到`parseData`方法中,通过返回一个`Map`来返回`djList`和`messageList`。这样可以进一步简化`while`循环体,提高代码可读性和可维护性。
阅读全文