package com.crawler.util; import com.crawler.model.CrawlerData; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.io.File; import java.io.IOException; import java.util.List; public class JsonSerializer { private static final ObjectMapper objectMapper; static { objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); } private JsonSerializer() {} public static void serializeToFile(List dataList, String filePath) throws IOException { File file = new File(filePath); File parentDir = file.getParentFile(); if (parentDir != null && !parentDir.exists()) { parentDir.mkdirs(); } objectMapper.writeValue(file, dataList); } public static List deserializeFromFile(String filePath) throws IOException { File file = new File(filePath); if (!file.exists()) { throw new IOException("文件不存在: " + filePath); } return objectMapper.readValue(file, new TypeReference>() {}); } public static String toJsonString(List dataList) throws IOException { return objectMapper.writeValueAsString(dataList); } public static String toJsonString(CrawlerData data) throws IOException { return objectMapper.writeValueAsString(data); } public static List fromJsonString(String jsonString) throws IOException { return objectMapper.readValue(jsonString, new TypeReference>() {}); } public static CrawlerData fromJsonStringToSingle(String jsonString) throws IOException { return objectMapper.readValue(jsonString, CrawlerData.class); } }