SpringBoot jackson传入List引起的坑
一、jackson无法解析value为[]的json
当入参为{xxxx1:[1,2,3],xxxx2:[obj1,obj2,obj3]}时,springmvn controller接收入参写为Long[] xxxx1,无法解析,报错
解决方案:
1.@RequestBody只能使用一次
2.使用map接收,再用get获取

二、如上,当数组为POJO时,通过直接map.get然后强制转换,不能成功,使用的时候还是LinkedHashMap
解决方案:
1.先将LinkedHashMap转为json,再讲json转为对象,如下JsonUtils的convertObject方法,转换List使用convertObjectList方法
package com.performancetest.common.utils; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map; public class JsonUtils { /**
* <p>
* 对象转JSON字符串
* </p>
*/
public static String object2Json(Object obj) {
String result = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
result = objectMapper.writeValueAsString(obj);
} catch (IOException e) {
e.printStackTrace();
}
return result;
} public static Map object2Map(Object obj) {
String object2Json = object2Json(obj);
Map<?, ?> result = jsonToMap(object2Json);
return result;
} /**
* <p>
* JSON字符串转Map对象
* </p>
*/
public static Map<?, ?> jsonToMap(String json) {
return json2Object(json, Map.class);
} /**
* <p>
* JSON转Object对象
* </p>
*
*/
public static <T> T json2Object(String json, Class<T> cls) {
T result = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
result = objectMapper.readValue(json, cls);
} catch (IOException e) {
e.printStackTrace();
} return result;
} public static <T> T convertObject(Object srcObject, Class<T> destObjectType) {
String jsonContent = object2Json(srcObject);
return json2Object(jsonContent, destObjectType);
} public static <T> List convertObjectList(List<LinkedHashMap> list, Class<T> destObjectType){
List result =new ArrayList<>();
list.stream().forEach(x->{
result.add(convertObject(x,destObjectType));
});
return result;
} }
三、如上转换时,报出错,jackson转换DateFormat类型时,不支持yyyy-MM-DD HH-mm-ss格式的日期,报错
解决方案:
方案1.在Date类型上加@JsonFormat( pattern="yyyy-MM-dd HH:mm:ss"),如下
(弊端:每个字段都得加,麻烦,没从根本上解决问题,不推荐,推荐方案2)
@JsonFormat( pattern="yyyy-MM-dd HH:mm:ss")
private Date updateTime;
方案2.
1.重写DateFormat子类,解析的实收优先用yyyy-MM-dd HH:mm:ss类型解析,不行再用父类
(这里遇到一个坑,启动时报calendar空指针异常,所以在构造函数里加了
this.calendar = dateFormat.getCalendar(); )
package com.performancetest.config; import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date; public class MyDateFormat extends DateFormat { private DateFormat dateFormat; private SimpleDateFormat format1 = new SimpleDateFormat("yyy-MM-dd HH:mm:ss"); public MyDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
//要添加父类的calendar属性,否则会报空指针异常
this.calendar = dateFormat.getCalendar();
} @Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
return dateFormat.format(date, toAppendTo, fieldPosition);
} @Override
public Date parse(String source, ParsePosition pos) { Date date = null; try { date = format1.parse(source, pos);
} catch (Exception e) { date = dateFormat.parse(source, pos);
} return date;
} // 主要还是装饰这个方法
@Override
public Date parse(String source) throws ParseException { Date date = null; try { // 先按我的规则来
date = format1.parse(source);
} catch (Exception e) { // 不行,那就按原先的规则吧
date = dateFormat.parse(source);
} return date;
} // 这里装饰clone方法的原因是因为clone方法在jackson中也有用到
@Override
public Object clone() {
Object format = dateFormat.clone();
return new MyDateFormat((DateFormat) format);
}
}
2.将新写的子类关联到WebConfig中的MappingJackson2HttpMessageConverter Bean,如下代码
package com.performancetest.config; import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import java.text.DateFormat; @Configuration
public class WebConfig { @Autowired
private Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder; @Bean
public MappingJackson2HttpMessageConverter MappingJsonpHttpMessageConverter() { ObjectMapper mapper = jackson2ObjectMapperBuilder.build(); //MyDateFormate解决jackson反序列formdate不支持YYYY-MM-DD HH-mm-ss的格式
// ObjectMapper为了保障线程安全性,里面的配置类都是一个不可变的对象
// 所以这里的setDateFormat的内部原理其实是创建了一个新的配置类
DateFormat dateFormat = mapper.getDateFormat();
MyDateFormat myDateFormat = new MyDateFormat(dateFormat);
mapper.setDateFormat(myDateFormat); MappingJackson2HttpMessageConverter mappingJsonpHttpMessageConverter = new MappingJackson2HttpMessageConverter(
mapper);
return mappingJsonpHttpMessageConverter;
}
}
SpringBoot jackson传入List引起的坑的更多相关文章
- 记一次SpringBoot 开发中所遇到的坑和解决方法
记一次SpringBoot 开发中所遇到的坑和解决方法 mybatis返回Integer为0,自动转型出现空指针异常 当我们使用Integer去接受数据库中表的数据,如果返回的数据中为0,那么Inte ...
- springboot项目--传入参数校验-----SpringBoot开发详解(五)--Controller接收参数以及参数校验----https://blog.csdn.net/qq_31001665/article/details/71075743
https://blog.csdn.net/qq_31001665/article/details/71075743 springboot项目--传入参数校验-----SpringBoot开发详解(五 ...
- @RequestBody jackson解析复杂的传入值的一个坑;jackson解析迭代数组;jackson多重数组;jakson数组
一.实际开发的一个问题. 传入一个json数组,数组中还嵌套数组,运用springboot+Jpa框架,@RequestBody注解传入数据 Controller @ApiOperation(valu ...
- SpringBoot + Shiro + shiro.ini 的踩坑记录
0.写在前面的话 好久没写博客了,诶,好多时候偷懒直接就抓网上的资料丢笔记里了,也就没有自己提炼,偷懒偷懒.然后最近参加了一个网络课程,要交作业的那种,为了能方便看下其他同学的作业,就写了个爬虫把作业 ...
- Springboot JackSon
1. SpringBoot JSON工具包默认是Jackson,只需要引入spring-boot-starter-web依赖包,自动引入相应依赖包: <dependency> <gr ...
- springboot整合log4j2遇到的一个坑
背景 项目中使用springboot,需要用log4j2做日志框架 问题 项目启动报错:Could not initialize Log4J2 logging from classpath:log4j ...
- Springboot Jackson配置根本方案, 日期格式化, 时区设置生效
当项目集成配置的功能越来越多, 说不准哪个配置就影响到了什么. 比如你启用了EnableMvC, 默认配置文件配置的一些文件就失效了. 虽然约定大于配置,让springboot可以极简化构建, 但不熟 ...
- spring-boot配置静态资源映射的坑:properties文件不能添加注释
如此博文所述,Spring Boot 对静态资源映射提供了默认配置 默认将 /** 所有访问映射到以下目录:classpath:/staticclasspath:/publicclasspath:/r ...
- springboot整合mybatis遇到的那些坑
1.接口类(指*Mapper.java)在spring中注册的问题 当控制台打印如下信息: A component required a bean named '*Mapper' that could ...
随机推荐
- 2017乌鲁木齐网络赛 j 题
题目连接 : https://nanti.jisuanke.com/t/A1256 Life is a journey, and the road we travel has twists and t ...
- 解读express框架
#解读Express 框架 1. package.json文件:express工程的配置文件 2. 为什么可以执行npm start?相当于执行 node ./bin/www "script ...
- iframe的document操作
导语: 在我写网页代填插件的时候,有遇到拿不到input元素的时候,这时候我去看元素布局,发现有些网站登录那一块是用iframe标签写的,这时候我需要取到的那就是iframe标签下input元素 1. ...
- (转发)IOS高级开发~Runtime(二)
一些公用类: @interface ClassCustomClass :NSObject{ NSString *varTest1; NSString *varTest2; NSString *varT ...
- redis学习笔记(1)
最近在学习redis,做了比较详细的学习笔记,分享给大家,欢迎一起讨论和学习 第一部分,简单介绍redis 和 redis的基本操作 NoSQL的特点 : 数据库种类繁多,但是一个共同的特点都是去掉关 ...
- 多线程辅助类之CyclicBarrier(四)
CyclicBarrier是一个线程辅助类,和<多线程辅助类之CountDownLatch(三)>功能类似,都可以实现一组线程的相互等待.要说不通点,那就是CyclicBarrier在释放 ...
- makedown语法
文章转载至:https://blog.csdn.net/u014061630/article/details/81359144#1-%E5%BF%AB%E6%8D%B7%E9%94%AE 前言 写过博 ...
- 2018 Multi-University Training Contest 1 Balanced Sequence(贪心)
题意: t组测试数据,每组数据有 n 个只由 '(' 和 ')' 构成的括号串. 要求把这 n 个串排序然后组成一个大的括号串,使得能够匹配的括号数最多. 如()()答案能够匹配的括号数是 4,(() ...
- Aizu - 1386 Starting a Scenic Railroad Service (思维乱搞)
给你n个区间,求: 1:最多有多少区间与同一个区间相交. 2:相交部分的最大区间数目. Sample Input 1 4 1 3 1 3 3 6 3 6 Sample Output 1 2 2 Sam ...
- German Collegiate Programming Contest 2018
// Coolest Ski Route #include <iostream> #include <cstdio> #include <cstring> #inc ...