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


  • 2018-04-02 10:50:59

    mybatis 中的<![CDATA[ ]]>

    在使用mybatis 时我们sql是写在xml 映射文件中,如果写的sql中有一些特殊的字符的话,在解析xml文件的时候会被转义,但我们不希望他被转义,所以我们要使用<![CDATA[ ]]>来解决。

  • 2018-04-03 10:21:35

    jquery实时监听输入框值变化

    在做web开发时候很多时候都需要即时监听输入框值的变化,以便作出即时动作去引导浏览者增强网站的用户体验感。而采用onchange时间又往往是在输入框失去焦点(onblur)时候触发,有时候并不能满足条件。

  • 2018-04-03 10:22:20

    JQuery如何监听DIV内容变化

    这几天在做一个微博的接入,需要判断微博是否被关注,要检查微博标签的DIV是否有“已关注”的字符,但这个DIV的内容是微博JSSDK动态生成。$("#id").html()是获取不到我想要的内容。原因是当我们获取的时候内容还没有改变,所以获取不到,如果就想到监听这个DIV内容变化后,再来获取就个时候就能获取到了。于是产生新的问题,如何监听DIV的变化?

  • 2018-04-04 23:52:03

    PowerManager之PowerManager

    当你在做一些事情时,如果持续时间过长,那么一段时间后屏幕会灭掉,如果你想在你做这些事时屏幕始终保持点亮状态,那么你需要WakeLock的帮助。

  • 2018-04-07 23:35:16

    使用Intent传递对象的两种方式

    Intent 的用法相信你已经比较熟悉了,我们可以借助它来启动活动、发送广播、启动服务等。在进行上述操作的时候,我们还可以在Intent 中添加一些附加数据,以达到传值的效果,比如在FirstActivity 中添加如下代码:

  • 2018-04-10 14:59:59

    JS实现数组去重方法总结(六种方法)

    这篇文章给大家总结下JS实现数组去重方法(六种方法),面试中也经常会遇到这个问题。文中给大家引申的还有合并数组并去重的方法,感兴趣的朋友跟随脚本之家小编一起学习吧