【Java】【21】读写Json文件

本文介绍了两种在Java中读取JSON文件的方法:一种是使用通用读取方法将JSON转换为Map列表,另一种是通过定义实体类并使用ObjectMapper进行类型转换。提供了详细的代码示例,展示了如何处理文件路径、异常和数据类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

正文:

1,通用读取方法,返回map

    public static List<Map> JsonRead(HttpServletRequest request, String path) {
        List<Map> maps = null;
        String dir = request.getSession().getServletContext().getRealPath(path);
        System.out.println(path);
        System.out.println(dir);
        if (dir == null) {
            System.out.println("找不到数据");
            return null;
        }
        try {
            File file = new File(dir);
            if (!file.exists()) {
                file.createNewFile();
            }
            String str = FileUtils.readFileToString(file, "UTF-8");
            maps = (List) JSONArray.fromObject(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return maps;
    };

2,先定义好实体类

public static void test() {
    ObjectMapper mapper = new ObjectMapper();
    TypeFactory typeFactory = mapper.getTypeFactory();
    CollectionType collectionType = typeFactory.constructCollectionType(List.class, SpringMonthVo.class);
    List<SpringMonthVo> list = new ArrayList<>();
    try {
        InputStream is = SpringMonthVo.class.getResourceAsStream("/springMonth.json");
        list = mapper.readValue(is, collectionType);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

见我的博客的<13,是否是中国春节月>

【Java】【19】Date Calendar相关 - 花生喂龙 - 博客园
https://www.cnblogs.com/huashengweilong/p/10825007.html

参考博客:

java如何读写json文件 - <&nbsp/> - 博客园
https://www.cnblogs.com/zhangdiIT/p/7590472.html

转载于:https://www.cnblogs.com/huashengweilong/p/10909521.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值