Jackson轉換為Collection、Array


1. Jackson轉化為Array

注意的地方就是實體類一定要有無參的構造方法,否則會報異常

//com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.example.jackjson.UnmarshallCollectionOrArray$User` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
package com.example.jackjson;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import org.assertj.core.util.Lists;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author: GuanBin
 * @date: Created in 下午2:33 2019/8/31
 */
public class UnmarshallCollectionOrArray {

    @Test
    public void unmarshallToArray() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        ArrayList<User> users = Lists.newArrayList(new User("tom", 10), new User("sam", 11));
        String str = mapper.writeValueAsString(users);
        System.out.println("user json:" + str);
        //若user沒無參構造方法會報錯
        //com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.example.jackjson.UnmarshallCollectionOrArray$User` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
        // at [Source: (String)"[{"name":"tom","age":10},{"name":"sam","age":11}]"; line: 1, column: 3] (through reference chain: java.lang.Object[][0])
        User[] userArray = mapper.readValue(str, User[].class);
        Assert.assertTrue(userArray[0] instanceof User);
    }

 

    static class User {
        public User() {
        }

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        private String name;
        private int age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}

2. Jackson轉化為list

 1)如果直接使用mapper.readValue(str, List.class); 雖然不會異常,但是list中的每個元素都是LinkedHashMap,而強轉為User會報錯;故如果轉化為List<User> 用此方法是不行的

 @Test
    public void unmarshallToList() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        ArrayList<User> users = Lists.newArrayList(new User("tom", 10), new User("sam", 11));
        String str = mapper.writeValueAsString(users);
        System.out.println("user json:" + str);
        //若user沒無參構造方法會報錯
        //com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.example.jackjson.UnmarshallCollectionOrArray$User` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
        // at [Source: (String)"[{"name":"tom","age":10},{"name":"sam","age":11}]"; line: 1, column: 3] (through reference chain: java.lang.Object[][0])
        List list = mapper.readValue(str, List.class);
        Assert.assertTrue(list.get(0) instanceof LinkedHashMap);
    }

2) 正確轉化為list的有兩種方式

     1. 使用TypeReference

        List<User> list = mapper.readValue(str, new TypeReference<List<User>>() { });

    @Test
    public void unmarshallToListOneWay() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        ArrayList<User> users = Lists.newArrayList(new User("tom", 10), new User("sam", 11));
        String str = mapper.writeValueAsString(users);
        System.out.println("user json:" + str);
        //若user沒無參構造方法會報錯
        //com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.example.jackjson.UnmarshallCollectionOrArray$User` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
        // at [Source: (String)"[{"name":"tom","age":10},{"name":"sam","age":11}]"; line: 1, column: 3] (through reference chain: java.lang.Object[][0])
        List<User> list = mapper.readValue(
                str, new TypeReference<List<User>>() { });
        Assert.assertTrue(list.get(0) instanceof User);
    }

    2. 獲取CollectionType

       CollectionType javaType = mapper.getTypeFactory().constructCollectionType(List.class, User.class);

       List<User> list = mapper.readValue(str, javaType);

    @Test
    public void unmarshallToListTwoWay() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        ArrayList<User> users = Lists.newArrayList(new User("tom", 10), new User("sam", 11));
        String str = mapper.writeValueAsString(users);
        System.out.println("user json:" + str);
        //若user沒無參構造方法會報錯
        //com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.example.jackjson.UnmarshallCollectionOrArray$User` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
        // at [Source: (String)"[{"name":"tom","age":10},{"name":"sam","age":11}]"; line: 1, column: 3] (through reference chain: java.lang.Object[][0])

        CollectionType javaType = mapper.getTypeFactory().constructCollectionType(List.class, User.class);
        List<User> list = mapper.readValue(str, javaType);
        Assert.assertTrue(list.get(0) instanceof User);
    }

 

 

 

注意:以上轉化過程都要求實體有無參的構造方法,否則會報異常

demo test:https://github.com/BinbinGuan/rabbitMq-test/commit/2c27f547ff4fdb249cd0d64294e3855d00993a96


免責聲明!

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



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