You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.9 KiB
55 lines
1.9 KiB
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);
|
|
}
|
|
}
|