Jackson converted Collection, Array

1. Jackson into Array

Constructor local attention is the entity class must be no-argument, otherwise they will be reported abnormal

//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 {
        Mapper ObjectMapper= new new ObjectMapper (); 
        the ArrayList <the User> Users = Lists.newArrayList ( new new the User ( " Tom " , 10 ), new new the User ( " SAM " , . 11 )); 
        String STR = mapper.writeValueAsString (Users); 
        . the System OUT . the println ( " user JSON: " + STR);
         // if the user is not being given constructor with no arguments
         //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 converted to list

 1) If the direct use mapper.readValue (str, List.class); though not unusual, but the list is a LinkedHashMap each element, and strong Switch User being given; if it is converted to List <User> with this the method does not work

 @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) right into a list of two ways

     1.使用Type Reference

        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. Get 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);
    }

 

 

 

Note: The above conversion process requires no-argument constructor entity, otherwise they will be reported abnormal

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

Guess you like

Origin www.cnblogs.com/guanbin-529/p/11441805.html