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

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

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

    public static void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count); 将指定数目的字 ...

  2. 关于struts2的checkboxlist、select等标签发生could not be resolved as a collection/array/map/enumeration/iterator type异常的记录

    1 刚进入该界面的时候发生错误,原因是 list="roles"中的这个集合是空的,导致错误 解决办法很简单,不能让list为空 2 刚进入该界面的时候list是有数据的,当点击提 ...

  3. List转换为数组Array的方法

    List<String> list = new ArrayList<String>(); list.add("str1"); list.add(" ...

  4. ibatis遍历数组:ParameterObject or property was not a Collection, Array or Iterator.

    这个问题在使用ibatis的<iterate></iterate>时出现的,很简单,但是蛋疼了很久,记下来 首先从错误提示看,明显意思是你给出ibatis的参数不对路,人家不认 ...

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

    本文内容 高级 Jackson Marshalling 只序列化符合自定义标准的字段 把 Enums 序列化成 JSON 对象 JsonMappingException(没有找到类的序列化器) Jac ...

  6. Mybatis中的collection、association来处理结果映射

    前不久的项目时间紧张,为了尽快完成原型开发,写了一段效率相当低的代码. 最近几天闲下来,主动把之前的代码优化了一下:)   标签:Java.Mybatis.MySQL 概况:本地系统从另外一个系统得到 ...

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

    转自:http://blog.csdn.net/wj3319/article/details/9025349 在SQL开发过程中,动态构建In集合条件查询是比较常见的用法,在Mybatis中提供了fo ...

  8. Jackson如何使JSON输出变得优雅?

    本篇文章翻译自:How to enable pretty print JSON output (Jackson) 在这篇文章中,我们将教你如何利用Jackson Library在控制台或者JSP页面优 ...

  9. MyBatis的foreach语句详解 list array map

    foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合.foreach元素的属性主要有 item,index,collection,open,separator,close.it ...

随机推荐

  1. zbar解析二维码demo

    开发环境;ubuntu 18.04 IDE:clion 2019 源文件.cpp #include <opencv2/opencv.hpp> #include <zbar.h> ...

  2. <数据结构>BinarySearchTree的基本操作总结

    目录 ADT 结构声明 核心操作集 各操作实现 Find(),Insert(),Delete() Traverse():前中后.层 ADT 结构声明 #include<stdio.h> # ...

  3. Kafka版本介绍Version2.4.0

    1.说明 Kafka的版本从0.11.0.X到1.0.X, 再到2.0.X大版本, 其实没有经过几个版本, 只是版本号变化较大. 2.最新发布版本 截止本文章2020年2月22号发布时, Kafka ...

  4. Pytest_fixture(9)

    什么是fixture fixture是pytest特有的功能,使用装饰器 @pytest.fixture 标记的函数在其他函数中能被当作参数传入并被调用. fixture有明确的名字,在其他函数,模块 ...

  5. centos7 安装locate

    使用locate my.cnf命令可以列出所有的my.cnf文件 yum  -y install mlocate 原因是安装完后没有更新库 更新库:updatedb

  6. solr -window 安装与启动

    1.下载 官网路径   https://solr.apache.org/downloads.html 为了稳定,我用 5.4.1 版本的 ,   这是下载地址 https://archive.apac ...

  7. spring security 在controller层 方法级别使用注解 @PreAuthorize("hasRole('ROLE_xxx')")设置权限拦截 ,无权限则返回403

    1.前言 以前学习的时候使用权限的拦截,一般都是对路径进行拦截 ,要么用拦截器设置拦截信息,要么是在配置文件内设置拦截信息, spring security 支持使用注解的形式 ,写在方法和接口上拦截 ...

  8. react中Fragment组件

    什么是Fragment?在我们定义组件的时候return里最外层包裹的div往往不想渲染到页面,那么就要用到我们的Fragment组件了,具体使用如下: import React, { Compone ...

  9. css编写规则BEM

    简单来说,格式如下: .block { /* styles */ } .block__element { /* styles */ } .block--modifier { /* styles */ ...

  10. 微服务架构 | 3.2 Alibaba Nacos 注册中心

    目录 前言 1. Nacos 基础知识 1.1 Nacos 命名方式 1.2 Nasoc 是什么 1.3 Nacos 的 4 个关键特性 1.4 Nacos 生态图 1.5 Nacos 架构图 1.6 ...