Browse Source

上传文件至 'project/util'

main
HuangZhikai 3 weeks ago
parent
commit
f89b74dae7
  1. 55
      project/util/JsonSerializer.java

55
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<CrawlerData> 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<CrawlerData> deserializeFromFile(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
throw new IOException("文件不存在: " + filePath);
}
return objectMapper.readValue(file, new TypeReference<List<CrawlerData>>() {});
}
public static String toJsonString(List<CrawlerData> dataList) throws IOException {
return objectMapper.writeValueAsString(dataList);
}
public static String toJsonString(CrawlerData data) throws IOException {
return objectMapper.writeValueAsString(data);
}
public static List<CrawlerData> fromJsonString(String jsonString) throws IOException {
return objectMapper.readValue(jsonString, new TypeReference<List<CrawlerData>>() {});
}
public static CrawlerData fromJsonStringToSingle(String jsonString) throws IOException {
return objectMapper.readValue(jsonString, CrawlerData.class);
}
}
Loading…
Cancel
Save