读取文件将其转换为实体类对象(前提文件中内容是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
    评论
要将MyBatisJSON字符串转换对象,你需要进行以下步骤: 1. 首先,在你的实体定义对应的属性,确保属性的类型与数据库存储的JSON字符串所表示的类型相匹配。在你的实体,你应该有一个名为limiting的属性,类型为Object。 2. 然后,在你的实体类的构造函数,将limiting参数的类型设置为Object,而不是ParameterLimiting。这是因为在数据库存储的是JSON字符串,而不是具体的ParameterLimiting对象。 3. 接下来,创建一个类型处理器(TypeHandler)来完成从JSON字符串对象转换。你可以继承BaseTypeHandler类,并指定泛型为ParameterLimiting。在该类型处理器,你需要实现一些方法,例如setNonNullParameter用于将对象转换JSON字符串并写入数据库,getNullableResult用于从数据库读取JSON字符串并将其转换对象。在setNonNullParameter方法,你可以使用JSON.toJSONString方法将对象转换JSON字符串,并调用PreparedStatement的setObject方法将其写入数据库。 4. 最后,在你的MyBatis的配置文件,将该类型处理器注册为对应属性的类型处理器。你需要在<mappers>标签下添加一个<typeHandlers>标签,并在其配置你的类型处理器。在配置,你需要指定对应属性的Java类型以及该属性在数据库的JDBC类型。 总结起来,将MyBatisJSON字符串转换对象的过程包括:在实体定义属性,修改构造函数,创建类型处理器,并在配置文件注册该类型处理器。这样,在查询结果集时,MyBatis就会自动将数据库JSON字符串转换为对应的对象

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值