Open ichengzi opened 3 years ago
// JavaTimeModule 依赖 <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </dependency>
@Slf4j public final class JsonUtils { private static ObjectMapper objectMapper = new ObjectMapper(); static { // 如果json字段比较多,而我们对象只需要部分字段,这时反序列化时会报错,如下配置可以在反序列化时忽略json中多余的字段了 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // java.util.date String strFormat = "yyyy-MM-dd HH:mm:ss"; objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); objectMapper.setDateFormat(new SimpleDateFormat(strFormat)); // java.time.localDateTime JavaTimeModule javaTimeModule = new JavaTimeModule(); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(strFormat); javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter)); javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter)); objectMapper.registerModule(javaTimeModule); } @SneakyThrows public static String toJson(Object obj) { if (obj == null) { return ""; } try { return objectMapper.writeValueAsString(obj); } catch (Exception e) { log.error("to json error", e); return ""; } } }
// test public class JsonUtilsTest { @Test public void toJson() { Map<String, Object> items = Maps.newLinkedHashMap(); items.put("java.util.date", new Date()); items.put("java.time.localDateTime", LocalDateTime.now()); items.put("java.time.LocalDate", LocalDate.now()); items.put("java.time.LocalTime", LocalTime.now()); String s = JsonUtils.toJsonIndent(items); System.out.println(s); /*{ "java.util.date" : "2021-01-05 13:53:26", "java.time.localDateTime" : "2021-01-05 13:53:26", "java.time.LocalDate" : "2021-01-05", "java.time.LocalTime" : "13:53:26.607" }*/ assertTrue(items != null); } }