1.项目场景:
项目场景:Java项目中一个需求是把数据信息转换为json格式文件放在服务器指定目录,在第三方系统反查信息时再取到文件中数据返回给第三方。
2.功能实现
1、向指定目录写Json文件
public static void writeJsonTo(String result, String filePath) {
log.info("--------->json文件路径:{}", filePath);
FileWriter fr = null;
try {
File file = new File(filePath);
int tryNum = 0;
if (!file.getParentFile().exists()) {
boolean fileExists = file.getParentFile().mkdirs();
while (tryNum < 6 && !fileExists) {
Thread.sleep(500);
fileExists = file.getParentFile().mkdirs();
tryNum++;
}
}
fr = new FileWriter(file);
fr.write(result);
fr.flush();
fr.close();
} catch (Exception e) {
log.error(e.getMessage(),e);
} finally {
if(fr != null){
try {
fr.close();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
2、读取文件内容转换成字符串
public static String readJsonFrom(File f) {
InputStream is = null;
String ret = null;
try {
is = new BufferedInputStream(new FileInputStream(f));
long contentLength = f.length();
ByteArrayOutputStream outstream = new ByteArrayOutputStream(contentLength > 0L ? (int)contentLength : 1024);
byte[] buffer = new byte[4096];
int len;
while((len = is.read(buffer)) > 0) {
outstream.write(buffer, 0, len);
}
outstream.close();
ret = new String(outstream.toByteArray(), "utf-8");
} catch (IOException var16) {
ret = "";
} finally {
if (is != null) {
try {
is.close();
} catch (Exception var15) {
}
}
}
return ret;
}
3、将字符串转换为ArrayNode数组
public static ArrayNode transToArrayNode(List<ScheduleInfo> scheduleList ,String parentPath) {
ObjectMapper mapper = new ObjectMapper();
ArrayNode arrayNode = mapper.createArrayNode();
scheduleList.forEach((info) -> {
String filePath = parentPath + info.getId() + ".json";
File file = new File(filePath);
if (file.exists()) {
String json = ScheduleUtil.readJsonFrom(file);
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(json);
} catch (IOException e) {
e.printStackTrace();
log.error(e.getMessage(), e);
}
arrayNode.add(jsonNode);
}
});
return arrayNode ;
}
``
3.Jackson中的JsonNode,ObjectNode,ArrayNode理解
ObjectNode是一个JSON对象节点,ArrayNode就是一个数组,可以包含多个ObjectNode。
1. JsonNode
JsonNode是Jackson中为了处理JOSN文本的树模型(tree model)。可以将JSON文本转成JsonNode,也可以将JsonNode转成JOSN文本。JsonNode是只读的,不可修改,用它可以方便的获取JSON中某字段的值
。
2. JsonNode VS ObjectNode
ObjectNode和ArrayNode都是JsonNode类的扩展,不同的是JsonNode是只读的,而ObjectNode和ArrayNode是可以修改的
。