zoukankan      html  css  js  c++  java
  • json jackson

    1.引入依赖

            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.8.3</version>
            </dependency>

    2.添加 conventer

        <mvc:annotation-driven>
            <mvc:message-converters>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="objectMapper" ref="objectMapper" />
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
    
        <bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
            p:indentOutput="false" p:simpleDateFormat="yyyy-MM-dd'T'HH:mm:ss.SSSZ" />

    indentOutput 缩进打印,false 无缩进 ,true 有缩进(格式化)

    {
      "b" : "你好",
      "a" : "2016-10-06T14:54:16.918+0800"
    }
    {"b":"你好","a":"2016-10-06T14:57:33.724+0800"}

    simpleDateFormat 可以将日期类型自动转为指定格式字符串

    具体用法可以查看该类

    MappingJackson2HttpMessageConverter

    By default, this converter supports application/json and application/*+json with UTF-8 character
    set. This can be overridden by setting the supportedMediaTypes property.

    这样重写

        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>application/json;charset=UTF-8</value>
                </list>
            </property>
        </bean>

    3. 设置controller 的 response

    关于controller 返回时由哪个 conventer 处理的问题

    首先 如果不是加 @ResponseBody 则由viewresolver 处理

    在 @Controller + @ResponseBody = @RestController

    You can use the new @RestController annotation with Spring MVC applications, removing the need to add @ResponseBody to each of your @RequestMapping methods.

    这种情况下 converter就生效了,会根据 Content-Type:text/html;charset=ISO-8859-1 类型分配给具体的 converter 处理

    默认有一个 

    2016-10-06 15:39:48 DEBUG RequestResponseBodyMethodProcessor:250 - Written [你好] as "text/html" using [org.springframework.http.converter.StringHttpMessageConverter@407305a3]

    这个默认的 StringHttpMessageConverter 使用的编码是 

    public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

    可以覆盖这个 converter

                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <constructor-arg value="UTF-8" />
                </bean>

    有这么多 HttpMessageConverter 视情况增加到 <mvc:message-converters>...

  • 相关阅读:
    js 导航栏多项点击显示下拉菜单代码
    当你工作与生活迷茫时可以来看看 shuke
    vs code使用指南
    两列
    三列浮动中间宽度自适应
    两列右列宽度自适应
    word文档巧替换(空行替换、空格替换、软回车替换成硬回车)
    统计单元格内指定的字符数方法 ,方法 一好用
    umi ui 构建时出现 spawn sh ENOENT 报错的解决方法
    新的博客,声明一下以前的域名作废了
  • 原文地址:https://www.cnblogs.com/zno2/p/5934038.html
Copyright © 2011-2022 走看看