From f89b74dae70014e8a2488eca9a36f477dbaa5802 Mon Sep 17 00:00:00 2001 From: HuangZhikai <386754646@qq.com> Date: Sun, 31 May 2026 14:52:34 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6=E8=87=B3?= =?UTF-8?q?=20'project/util'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- project/util/JsonSerializer.java | 55 ++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 project/util/JsonSerializer.java diff --git a/project/util/JsonSerializer.java b/project/util/JsonSerializer.java new file mode 100644 index 0000000..aa68b8a --- /dev/null +++ b/project/util/JsonSerializer.java @@ -0,0 +1,55 @@ +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); + } +} \ No newline at end of file