package com.bananain.cplan.spp.utils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
@UtilityClass
public class JacksonUtil {
public static final ObjectMapper objectMapper = new ObjectMapper();
static {
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
objectMapper.registerModule(javaTimeModule);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
@SneakyThrows
public static <T> T parse(String json, Class<T> clazz) {
if (StringUtils.isBlank(json)) {
return null;
}
return objectMapper.readValue(json, clazz);
}
@SneakyThrows
public static <T> List<T> parseList(String json, Class<T> c) {
if (StringUtils.isBlank(json)) {
return Collections.emptyList();
}
return objectMapper.readerForListOf(c).readValue(json);
}
@SneakyThrows
public static String toJson(Object obj) {
return objectMapper.writeValueAsString(obj);
}
}