Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

java-jackson-时间格式化-javaTimeModule #27

Open
ichengzi opened this issue Jan 5, 2021 · 0 comments
Open

java-jackson-时间格式化-javaTimeModule #27

ichengzi opened this issue Jan 5, 2021 · 0 comments
Labels

Comments

@ichengzi
Copy link
Owner

ichengzi commented Jan 5, 2021

// 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);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant