前言
读取文件——>转换为字符串——>生成实体类
一、具体实现
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
}
]
总结
这种工具类,有一个就够了,能用很久很久,但是还得与时俱进才行