读取JSON文件,并转化为指定class

该代码示例展示了如何从指定路径的JSON文件中读取数据,将JSON对象转换为JSONArray,然后进一步解析为自定义实体类Xxx的列表。主要方法包括使用FileReader和InputStreamReader读取文件内容,JSONObject解析JSON数据以及将JSON数据映射到Java对象。
摘要由CSDN通过智能技术生成
@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;
     }
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值