背景:java - spring-boot,mybatis,mysql
获取JSON文件
一、读取本地json
- 使用java类:java/io(File,FileInputStream)
/**
2. 读取本地JSON文件
3. 文件存放于resource->static->test.json
4.
5. @param pathName 文件路径"src/main/resources/static/customArea.json"
6. @return json 字符串
*/
private String readLocalJSONFile(String pathName) throws IOException {
File jsonFile = new File(pathName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
int ch;
StringBuilder sb = new StringBuilder();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
return sb.toString();
}
- 使用spring框架提供的:PathMatchingResourcePatternResolver
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// 读取 resources 下的系统消息模板 json 文件
Resource templateJson = resolver.getResource("template/msg_template/msg_template.json");
// JSON 数据转实体类
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootJsonNode = objectMapper.readTree(templateJson.getInputStream());
List<MsgTemplateEntity> msgTemplateEntityList = CollUtil.newArrayList();
if (rootJsonNode.isArray()) {
Iterator<JsonNode> templates = rootJsonNode.elements();
while (templates.hasNext()) {
JsonNode jsonNode = templates.next();
JsonNode codeNode = jsonNode.get("code");
JsonNode titleNode = jsonNode.get("title");
JsonNode contentNode = jsonNode.get("content");
JsonNode remarkNode = jsonNode.get("remark");
MsgTemplateEntity msgTemplateEntity = MsgTemplateEntity.builder()
.code(codeNode.asText())
.title(titleNode.asText())
.content(contentNode.asText())
.build();
msgTemplateEntityList.add(msgTemplateEntity);
}
}
}
- 使用hutool类:FileReader
/**
* hutool读取本地JSON文件
* 文件存放于resource->static->test.json
*
* @param pathName 文件路径
* @return json 字符串
*/
private String readLocalJSONFile(String pathName) {
FileReader fileReader = new FileReader("static/test.json");
return fileReader.readString();
}
二、请求接口返回数据
工具:hutool -> HttpRequest类
// 构造json参数
JSONObject jsonParams = new JSONObject();
// 构造对象
HttpRequest request = new HttpRequest(url);
// 设置method:post请求
request.setMethod(Method.POST);
// 设置请求参数,json字符串或者xml字符串
request.body(jsonParams.toJSONString());
// 发送异步请求,参数:isAsync
HttpResponse response = request.execute(true);
// 处理结果
if (resp.isOk()) {
return = resp.body();
}
// 简写:String str = HttpRequest.post(cameraUrl).body(params.toJSONString()).execute(true).body();
接口返回内容 => 对象数组
工具:fastjson
// 获取到了json字符串
String str = readLocalJSONFile("E://test.json");
// 像前端一样处理json数据
JSONObject res = JSON.parseObject(str); // 先将res转换为json对象(state,message,data等内容)
JSONArray data = res.getJSONArray("data"); // 获取let data = res.data
List<MyObject> list = data.toJavaList(MyObject.class);// 通过.toJavaList(Class)转换为对象数组
list.forEach(item -> {
// 遍历处理data.map()
});
/* 当查询接口返回的字段和class的字段对应不上时候,通过@JSONField进行映射
@Getter @Setter @JSONField(name = "_id")
private String id;
*/
通过mybatis将对象数组存入数据库
// 批量插入
@Insert("<script>" +
"insert into camera(id) " +
"values " +
"<foreach collection='list' item='item' index='index' open="(" separator=',' close=")">" +
"#{item.id}" +
"</foreach>" +
"</script>")
int addBatch(@Param("list") List<MyObject> list);