读取JSON文件封装进对象

读取JSON文件,封装成对象

Gson、流

gson.fromJson

  1. 引入依赖
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

​ 2、

 public static Map<String,Object> readJsonFile(String fileName){
        Gson gson = new Gson();
        String json = "";
        File file = new File(fileName);
        try {
            Reader reader = new InputStreamReader(new FileInputStream(file),"utf-8");
            int ch = 0;
            StringBuffer buffer = new StringBuffer();
            while ((ch = reader.read())!= -1){
                buffer.append((char) ch);
            }
            reader.close();
            json = buffer.toString();
            return gson.fromJson(json,Map.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

测试

    public static void main(String[] args) {  
       System.out.println(readJsonFile("D:\\workspace\\ZhuStudy\\Demo01\\src\\main\\resources\\abc.json"));
    }
}
posted @   风冰水  阅读(169)  评论(0编辑  收藏  举报
编辑推荐:
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
阅读排行:
· 本地部署 DeepSeek:小白也能轻松搞定!
· 基于DeepSeek R1 满血版大模型的个人知识库,回答都源自对你专属文件的深度学习。
· 在缓慢中沉淀,在挑战中重生!2024个人总结!
· 大人,时代变了! 赶快把自有业务的本地AI“模型”训练起来!
· Tinyfox 简易教程-1:Hello World!
点击右上角即可分享
微信分享提示