ObjectMapper序列化時間


springmvc默認的消息轉換器是使用的MappingJackson2HttpMessageConverter, 其核心類就是ObjectMapper.

 

先看一下面一個示例

@RestController
public class TestObjectMapperController {

    @GetMapping("/getUser")
    public User getUser() {
        User user = new User();
        user.setUId("1");
        user.setDate(new Date());
        user.setLocalDateTime(LocalDateTime.now());
        return user;
    }

}

@Data
class User {
    private String uId;
    private Date date;
    private LocalDateTime localDateTime;
}

 

啟動springboot項目,瀏覽器請求/getUser接口,結果就是下面這個破樣子

序列化后的時間格式明顯不是我們想要的, 可以通過以下配置對其進行修改

@Configuration
public class ObjectMapperConfig {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customJackson() {
        return jacksonObjectMapperBuilder -> {
            //若POJO對象的屬性值為null,序列化時不進行顯示
            jacksonObjectMapperBuilder.serializationInclusion(JsonInclude.Include.NON_NULL);

            //針對於Date類型,文本格式化
            jacksonObjectMapperBuilder.simpleDateFormat("yyyy-MM-dd HH:mm:ss");

            //針對於JDK新時間類。序列化時帶有T的問題,自定義格式化字符串
            JavaTimeModule javaTimeModule = new JavaTimeModule();
            javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            jacksonObjectMapperBuilder.modules(javaTimeModule);

        };
    }
}

 

添加以下配置后, 重啟項目,請求/getUser接口,結果如下

 

 

 

===============補充示例===============

public class TestObjectMapper {
    @Test
    public void test1() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        //POJO無public的屬性或方法時,不報錯
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        //null值字段不顯示
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //美化JSON輸出
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

//        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);  // 序列化JSON串時,在值上打印出對象類型
        A a = new A();
        B b = new B();
        b.setSalary(100.5D);
        b.setAge(18);
        a.setB(b);
        a.setId("123");
        a.setUsername("admin");
        a.setDate(new Date());
        String string = objectMapper.writeValueAsString(a);   //解析對象
        System.out.println(string);
        
    }
}

@Data
class A {
    private String id;
    private String username;
    private Date date;
    private B b;
}

@Data
class B {
    private Double salary;
    private Integer age;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM