1 changed files with 55 additions and 0 deletions
@ -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…
Reference in new issue