spring boot2之Jackson和ObjectMapper


在spring boot中,默認使用Jackson來實現java對象到json格式的序列化與反序列化。如第3篇講的@RequestBody和@ResponseBody的轉換,最終都是由Jackson來完成的。

 

ObjectMapper基本用法

Jackson的轉換是通過ObjectMapper對象來實現的,spring boot內部自動配置了一個ObjectMapper對象,我們可以直接用。

    @Autowired
    ObjectMapper objectMapper;
    
    @GetMapping("/hello")
    public void hello() throws IOException {
        
        User user1 = new User();
        user1.setId("1");
        user1.setName("tom");
        //序列化
        String json = objectMapper.writeValueAsString(user1);
        System.out.println(json);
        
        //反序列化
        User user2 = objectMapper.readValue(json, User.class);
        System.out.println(user2.getId());
        System.out.println(user2.getName());

writeValueAsString:是將參數中的java對象序列化為json字符串。

readValue:是將json字符串反序列化為java對象,User.class就是指定對象的類型。

 

泛型的反序列化

上面的方法同樣適用於集合類型,但如果是包含泛型的集合則需要使用以下兩種方法之一
        String json = "[{\"id\":\"1\",\"name\":\"tom\"},{\"id\":\"2\",\"name\":\"jerry\"}]";
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, User.class);
        List<User> list = objectMapper.readValue(json, javaType);

或者

        String json = "[{\"id\":\"1\",\"name\":\"tom\"},{\"id\":\"2\",\"name\":\"jerry\"}]";
        List<User> list = objectMapper.readValue(json, new TypeReference<List<User>>() {})

 

properties常用參數配置

 

#日期類型格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#日期類型使用中國時區
spring.jackson.time-zone=GMT+8
#序列化所有參數
spring.jackson.default-property-inclusion=always

 

 

spring.jackson.date-format:當序列化對象中包含日期類型的參數時,配置其轉換的格式,如yyyy-MM-dd HH:mm:ss

spring.jackson.time-zone:有些日期數據可能並不是中國時區,設置GMT+8可將其轉換為中國時區

spring.jackson.default-property-inclusion:需要進行序列化的參數,默認值為always指所有。還可配置如下值:

    non_null:為null的參數不序列化。
    non_empty:為空的參數不序列化,如""、null、沒有內容的new HashMap()等都算。Integer的0不算空。
    non_default:為默認值的參數不序列化,以上都算。另外,如Integer的0等也算默認值。

不序列化的參數:指java對象轉換為json字符串時,其中不包含該參數。如當id=1,name=null時,always默認序列化為

 

如配置了不序列化為null的值,結果如下

 

 

 

常用注解

@JsonProperty:如下,假如id=1,轉換為json時將輸出key=1

@JsonProperty("key")
Integer id

@JsonIgnore:如下,不序列化id參數

@JsonIgnore
Integer id;

 


免責聲明!

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



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