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

原文地址:https://www.cnblogs.com/guanbin-529/p/11441805.html

时间: 2024-10-30 04:39:17

Jackson转换为Collection、Array的相关文章

C#中使用Buffer.BlockCopy()方法将string转换为byte array的方法:

public static void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count); 将指定数目的字节从起始于特定偏移量的源数组复制到起始于特定偏移量的目标数组. /// <summary> /// C#中使用Buffer.BlockCopy()方法将string转换为byte array的方法 /// </summary> /// <param name="str&

表单form类型数据转换为数组array

Http的请求类型: Content-Type: application/x-www-form-urlencoded 数据格式比如: mc_gross=399.00&protection_eligibility=Eligible&address_status=confirmed&payer_id=XEMQ4LGLL3E8U&address_street=%BF%C6%D4%B0%C2%B72%BA%C5A8%D2%F4%C0%D6%B4%F3%CF%C3&payme

oracle collection

Collections Overview 一.Types of Collections 1.Associative arrays 数组      它是同种类型的一维.无边界的稀疏集合,只能用于 PL/SQL.      DECLARE TYPE t_name IS TABLE OF varchar2(10) INDEX BY PLS_INTEGER; --创建 Collection              i_name t_name;      --创建 instance           

Android 高级 Jackson Marshalling(serialize)/Unmarshalling(deserialize)

本文内容 高级 Jackson Marshalling Serialize Only Fields that meet a Custom Criteria with Jackson Serialize Enums as JSON Objects JsonMappingException (No serializer found for class) Jackson – Custom Serializer 高级 Jackson Unmarshalling Unmarshall to Collect

[转]Java之Collection/Map

转自: http://www.cnblogs.com/mingcn/archive/2010/10/22/JavaContainer.html Java复习笔记——容器知识点总结 Java中容器分两类,一种是单值的Collection,一种是储存键-值对的Map Collection 又分两种,Set和List,区别在于Set是不可重复的,而List是可重复的 Set 常用有两种:HashSet和TreeSet,其内部实现是一个Map,它的元素就相当于Map中的Key,而Value是一个Obje

java collection 集合源码分析(二) map

Map(接口) Map是一个独立的接口,内部包含一个Entry的接口,用于管理每个节点 public interface Map<K,V>{     interface Entry<K,V> {          } } AbstractMap 抽象类实现Map接口,常用的HashMap和TreeMap都继承此类 public abstract class AbstractMap<K,V> implements Map<K,V> 这个类下面提供了一个将Map

mybatis ForEach Collection集合等规范解析(转)

转自:http://blog.csdn.net/wj3319/article/details/9025349 在SQL开发过程中,动态构建In集合条件查询是比较常见的用法,在Mybatis中提供了foreach功能,该功能比较强大,它允许你指定一个集合,声明集合项和索引变量,它们可以用在元素体内.它也允许你指定开放和关闭的字符串,在迭代之间放置分隔符.这个元素是很智能的,它不会偶然地附加多余的分隔符.下面是一个演示示例:   <select id="findByIdsMap" r

MyBatis的foreach语句详解 list array map

foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合.foreach元素的属性主要有 item,index,collection,open,separator,close.item表示集合中每一个元素进行迭代时的别名,index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collectio

[JavaScript语法学习]全面介绍Array

Array Array可以包含任意数据类型,并通过索引来访问每个元素.直接给Array的length属性赋予一个新的值会导致Array大小的变化,其中未赋值的数据就是undefined. 因此不建议直接修改Array的大小,同时确保索引访问时不会出现索引越界. 属性 length prototype 方法 Array.isArray() Array.prototype.pop()   删掉最后一个元素 Array.prototype.push()  末尾添加若干元素 Array.prototyp