spring boot jackson的一些配置项

2019-12-03 16:38:10

参考地址 


ObjectMapper 的一些坑

问题描述

SpringMVC的注解@ResponseBody在以下情况使用时:

@ResponseBody
@RequestMapping("/your_url/act.do")
public Map<String, Object> yourMethod(){    // do your work...

    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("code", 0);
    resultMap.put("data", new Object());// 序列化 new Obejct()}

会报如下错误

 DefaultHandlerExceptionResolver:134 : Resolving exception from handler []: org.springframework.http.converter.HttpMessageNotWritableException: 
 Could not write JSON: No serializer found for class java.lang.Object and no properties discovered to create BeanSerializer 
 (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) ;

意思是没有找到可用于Object的序列化器,也没有找到属性去创建BeanSerializer。
后面的接着提示了解决方法:(to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)

解决方案

为SpringMVC里默认序列化使用的 com.fasterxml.jackson.databind.ObjectMapper 设置其属性 SerializationFeature.FAIL_ON_EMPTY_BEANS 为false。
貌似没办法直接在XML配置里设置。只能自定义 com.fasterxml.jackson.databind.ObjectMapper 类进行设置,然后再配置xml。过程如下:

// 继承 ObjectMapper 类public class CustomMapper extends ObjectMapper{ 
    public CustomMapper() {        this.setSerializationInclusion(JsonInclude.Include.NON_NULL);        // 设置 SerializationFeature.FAIL_ON_EMPTY_BEANS 为 false
        this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }
}
<!-- Spring MVC 配置 --><mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>text/plain;charset=UTF-8</value>
                    <value>text/html;charset=UTF-8</value>
                </list>
            </property>
        </bean>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>application/json; charset=UTF-8</value>
                    <value>application/x-www-form-urlencoded; charset=UTF-8</value>
                </list>
            </property>
            <!-- 配置 objectMapper 为我们自定义扩展后的 CustomMapper -->
            <property name="objectMapper">
                <bean class="com.king.framework.jackson.CustomMapper">
                </bean>
            </property>
        </bean>
    </mvc:message-converters></mvc:annotation-driven>


spirng boot 可以在配置文件中配置 ,也可以生成bean的时候修改。

一些配置项的意思如下。


ObjectMapper objectMapper = new ObjectMapper();
		
		//序列化的时候序列对象的所有属性
		objectMapper.setSerializationInclusion(Include.ALWAYS);
		
		//反序列化的时候如果多了其他属性,不抛出异常
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		
		//如果是空对象的时候,不抛异常
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		
		//取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
		objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
	ObjectMapper objectMapper = new ObjectMapper();
		//序列化的时候序列对象的所有属性
		objectMapper.setSerializationInclusion(Include.ALWAYS);
		//取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
		objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		
		Person person = new Person(1, "zxc", new Date());
		//这是最简单的一个例子,把一个对象转换为json字符串
		String personJson = objectMapper.writeValueAsString(person);
		System.out.println(personJson);
		
		//默认为true,会显示时间戳
		objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
		personJson = objectMapper.writeValueAsString(person);
		System.out.println(personJson);

————————————————
版权声明:本文为CSDN博主「zxc_user」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zxc_user/article/details/79713586


  • 2017-04-13 10:57:08

    webstorm 怎么关闭jshint

    You need to configure the inspections in Settings/Editor/Inspections, then in the list on the right, find JavaScript/JavaScript validity issues. That worked for me to remove the Chai warnings. (I am using the WebStorm 11 EAP at the moment.)

  • 2017-04-13 14:11:14

    MySQL中的describe关键字

    今天写代码的时候,有一个类的数据始终不能插入,老是提示在You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'describe, picPath1, picPath2, picPath3, picPath4, picPath5, agentId, belongStore' at line 1。因为用的是SSH进行插入,所以SQL语句不用自己写,检查了每个字段也没写错。

  • 2017-04-15 13:34:08

    Android官方技术文档翻译——清单合并

    一般情况下,有三种类型的清单文件需要合并成一个最终的应用程序清单,这里按照优先级顺序列出: Product flavors 和构建类型所指定的清单文件。 应用程序的主清单文件。 类库的清单文件。

  • 2017-04-15 21:47:44

    Android开发笔记——圆角和边框们

    在做Android界面开发时,我们往往希望它尽可能优美,尽可能显得专业。于是你看了看其他应用,哇,好多边框和圆角啊。你是不是也想给自己的应用加上边框和圆角效果?呃……那怎么做呢?如果你是从web前端跑到Android来的,那么我想你一定想到了不下三种解决方案。如用图片替代,用CSS3定义,用JS画。在Android中,其实也有类似的用法,本文将简单介绍两种Android圆角和边框的实现。

  • 2017-04-15 21:49:06

    Android样式的开发:Style篇

    前面铺垫了那么多,终于要讲到本系列的终篇,整合所有资源,定义成统一的样式。 哪些该定义成统一的样式呢?举几个例子吧:

  • 2017-04-15 23:54:49

    ViewPager+Fragment取消预加载以及禁止滑动

    取消预加载 网上了解了很多取消预加载的方法,里面提到了使用一个viewpager的public方法setOffscreenPageLimit 经过查看源码以及验证发现该方法是管理Viewpager预加载的页数,最低也是默认为一页(例如ViewPager一共有4页,当前手机屏幕显示第一页