读取JSON文件,并处理json数据(读取JSON中某个值)
需要处理的json文件
{ "code":200, "message":"Success", "data":{ "fileName":"aa.jpg", "filePath":"file/aa.jpg", "base64":"AhCL95h014sgbqPbR9BtOiWgF5t8U2ggQZJqDwwEbScC/5B/QzHK9zqdrvZEXEPQ1" }, "timestamp":229480701 }
1、使用fastjson,
//fastjson,
private static void readerMethod(String filePath) throws IOException {
File file = new File(filePath);
FileReader fileReader = new FileReader(file);
Reader reader = new InputStreamReader(new FileInputStream(file), "Utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
String jsonStr = sb.toString();
JSONObject jsonObject = JSON.parseObject(jsonStr);
// 获取json key-value 值
String data = jsonObject.getString("data");
JSONObject parse = (JSONObject) JSONObject.parse(data);
System.out.println(parse.getString("filePath"));
}
需要maven依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>2.0.21</version> </dependency>
2、jackson
private static void toMap(String filePath) throws IOException {
File file = new File(filePath);
ObjectMapper objectMapper = new ObjectMapper();
Map map = objectMapper.readValue(file, Map.class);
System.out.println(map.get("code"));
}
需要依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.3</version> </dependency>
3、nio
private static void nioMethod(String filePath) throws IOException {
String jsonString = new String(Files.readAllBytes(Paths.get(filePath)));
JSONObject obj = JSONObject.parseObject(jsonString);
String data = obj.getString("data");
JSONObject parse = (JSONObject) JSONObject.parse(data);
String result=parse.getString("filePath");
}
参考:https://blog.csdn.net/csdn_halon/article/details/120287992