private static final ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule()
.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyyMMdd")))
.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyyMMdd")))
);
}
maven依赖
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.16.1</version>
</dependency>
public class JsonUtil {
private static final ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule()
.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyyMMdd")))
.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyyMMdd")))
);
}
public static <T> T readJson(String path, Class<T> clazz) {
T t = null;
File file = new File(path);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
StringBuilder buffer =new StringBuilder();
String line =null;
while((line = reader.readLine())!= null){
buffer.append(line);
}
t = objectMapper.readValue(buffer.toString(), clazz);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return t;
}
public static <T> String writeJson(T t) {
String json = null;
try {
json = objectMapper.writeValueAsString(t);
} catch (IOException e) {
throw new RuntimeException(e);
}
return json;
}
}