读取文件将其转换为实体类对象(前提文件中内容是json字符串)


前言

读取文件——>转换为字符串——>生成实体类


一、具体实现

1、前提引入jar:

<dependency>  
    <groupId>com.fasterxml.jackson.core</groupId>  
    <artifactId>jackson-databind</artifactId>  
    <version>2.13.0</version> <!-- 使用你需要的版本 -->  
</dependency>

2、代码:

读取文件:这里涉及到相对路径和绝对路径的问题

相对路径:

import java.io.InputStream;  
import java.util.Scanner;  
  
public class RelativePathExample {  
    public static void main(String[] args) {  
        String relativePath = "文件/文本-case.json"; // 注意这里不需要src/main/resources前缀  
        InputStream inputStream = RelativePathExample.class.getClassLoader().getResourceAsStream(relativePath);  
        if (inputStream != null) {  
            try (Scanner scanner = new Scanner(inputStream, "UTF-8")) {  
                while (scanner.hasNextLine()) {  
                    System.out.println(scanner.nextLine());  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        } else {  
            System.out.println("文件未找到: " + relativePath);  
        }  
    }  
}

绝对路径

import java.nio.file.Files;  
import java.nio.file.Paths;  
import java.io.IOException;  
  
public class AbsolutePathExample {  
    public static void main(String[] args) {  
        String absolutePath = "/Users/xxx/xxx/xxx/xxx/src/main/resources/文件/case.json";  
        try {  
            byte[] fileContent = Files.readAllBytes(Paths.get(absolutePath));  
            // 这里你可以对fileContent进行处理,比如转换为字符串  
            String content = new String(fileContent);  
            System.out.println(content);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}

读取文件:

public static String readFile() {

        // 这里我们直接使用相对路径(相对于项目根目录)
        Path filePath = Paths.get("src/main/resources/case.json");
        StringBuilder content = new StringBuilder();
        // 使用try-with-resources来自动关闭流
        try (BufferedReader reader = Files.newBufferedReader(filePath)) {
            String line;
            // 逐行读取文件内容
            while ((line = reader.readLine()) != null) {
                content.append(line).append(System.lineSeparator());
            }
            // 展示文件内容
            System.out.println(content.toString());
        } catch (IOException e) {
            // 处理可能出现的异常
            e.printStackTrace();
            System.err.println("读取文件时出错:" + e.getMessage());
        }
        return content.toString();
    }

操作:


 public static void main(String[] args) throws JsonProcessingException {
        String jsonString = readFile(); // 这里放置你的JSON字符串
        System.out.println("最终生成的字符串为:\n" + jsonString);
        ObjectMapper mapper = new ObjectMapper();
        List<City> cityList = mapper.readValue(jsonString, mapper.getTypeFactory().constructCollectionType(List.class, City.class));
        System.out.println(cityList);
    }

补充:

更具json字符串结构创建对应的类:
我的类为:

@Data
class City {
    private String cityName;
    private int cityId;
    private List<CityDetail> childrenList;
    private int cityAdLevel;
}

@Data
class CityDetail {

    private String cityName;
    private int cityId;
    private int cityAdLevel;
}

文本信息

[
    {
      "cityName": "天津市",
      "cityId": 120000,
      "childrenList": [
        {
          "cityName": "天津市",
          "cityId": 120100,
          "cityAdLevel": 2
        }
      ],
      "cityAdLevel": 1
    },
    {
      "cityName": "江苏省",
      "cityId": 320000,
      "childrenList": [
        {
          "cityName": "镇江市",
          "cityId": 321100,
          "cityAdLevel": 2
        },
        {
          "cityName": "南通市",
          "cityId": 320600,
          "cityAdLevel": 2
        }
      ],
      "cityAdLevel": 1
    }
  ]

总结

这种工具类,有一个就够了,能用很久很久,但是还得与时俱进才行

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值