@SneakyThrows
public static void main(String[] args) {
String menu_json = "C:\\Users\\xxx\\Desktop\\json.txt";
JSONArray jsonArray = getJSONObject(menu_json);
// 需要转换的实体类
List<Xxx> workbenchMenuDTOS = menuJson.toJavaList(Xxx.class);
}
/**
* key 自己定义,返回什么也自己定义
* @param filePath
* @return
*/
private static JSONArray getJSONArray(String filePath) {
File jsonFile = new File(filePath);
String jsonData = getStr(jsonFile);
JSONObject jsonObject = JSONObject.parseObject(jsonData);
return jsonObject.getJSONArray("data");
}
/**
* 把一个文件中的内容读取成一个String字符串
* @param jsonFile
* @return
*/
public static String getStr(File jsonFile) {
String jsonStr = "";
try {
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
读取JSON文件,并转化为指定class
最新推荐文章于 2024-06-27 09:28:04 发布
该代码示例展示了如何从指定路径的JSON文件中读取数据,将JSON对象转换为JSONArray,然后进一步解析为自定义实体类Xxx的列表。主要方法包括使用FileReader和InputStreamReader读取文件内容,JSONObject解析JSON数据以及将JSON数据映射到Java对象。
摘要由CSDN通过智能技术生成