1、将Map写入json文件中
Map<String,String> map = getAllSystemFactorIDAndNameMap();
String filePath ="C:/Users/lin/stagingtest/backend-ft/src/test/resources/portfolio/template/factorNameAndId.json";
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File(filePath), map);
} catch (IOException e) {
e.printStackTrace();
}
2、将json文件中的数据通过key 取出来使用
public String getValue(String requestKey){
resourceFilePath = "/factor/request_data/factor.txt";
URL pathAsUrl = Class.class.getResource(resourceFilePath);
StringBuffer originalFileContent = new StringBuffer();
try{
BufferedReader br = new BufferedReader(new FileReader(pathAsUrl.getFile()));
String s = null;
while((s = br.readLine())!=null) {
originalFileContent.append(s + "\n");
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
//add slash '\' for all ' " ' in string: {"a":1, "b":2 } -> {\"a\":1, \"b\":2}
// return originalFileContent.toString().replace("\"", "\\\"");
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode mapper.readTree(originalFileContent.toString());
return jsonNode.get(requestKey).asText;
}