zoukankan      html  css  js  c++  java
  • springmvc+json

    1.在写我的springmvc demo时,由于要向前台返回相关信息,于是设置了@ResponseBody,但是要把对象转换成json格式,我却没有在xml文件里配置,所以报如下错误:
    HttpMediaTypeNotAcceptableException: Could not find acceptable representation。
    于是采用默认配置,即曾经号称“史上最快json”的Jackson

        <!-- 启用spring mvc 注解-->
        <mvc:annotation-driven>
            <!-- 启动JSON格式的配置 -->
            <mvc:message-converters>  
            <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="supportedMediaTypes">  
                    <list>  
                        <value>text/html;charset=UTF-8</value>  <!-- 避免IE出现下载JSON文件的情况 -->
                    </list>  
                </property>    
            </bean>  
            </mvc:message-converters>
        </mvc:annotation-driven>


    2.运行之后报错:Could not find acceptable representation

    原因是我忘记加入了jackson的两个包:jackson-core-asl-1.9.13和jackson-mapper-asl-1.9.13

    3.运行之后又报错:元素 'mvc:annotation-driven' 必须不含字符或元素信息项 [子级], 因为该类型的内容类型为空。发现我的xml里面的mvc命名空间中xsd版本是3.0的,但是我用的是4.0,后来想想去掉这个版本序号,默认的版本是什么呢?就试了下,好像是默认最新的(可以在myeclipse里面打开该链接,查看xsd文件)

    4.在网上查找资料时,看到了有关fastjson的文章,就看了看,发现网上对fastjson褒贬不一,褒的是fastjson就像它名字一样,序列化和反序列化速度很快,还有人专门做了测试;贬的是fastjson是阿里巴巴的温少写的,相关文档较少,遇到问题解决起来比较困难。但是由于我对阿里巴巴的执念,我还是用了fastjson

        <!-- 启用spring mvc 注解-->
           <mvc:annotation-driven>
            <!-- 启动JSON格式的配置 -->
               <mvc:message-converters>  
               <!-- 这里也可以自己定制class -->
            <bean id="jsonConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"><!-- 这里也可以自己定制class -->
                <property name="supportedMediaTypes">  
                    <list>  
                        <value>text/html;charset=UTF-8</value>  <!-- 避免IE出现下载JSON文件的情况 -->
                    </list>  
                </property>    
            </bean>  
        </mvc:message-converters>  
           </mvc:annotation-driven>


    备注:

     @ResponseBody:将内容或对象作为 HTTP 响应正文返回,使用@ResponseBody将会跳过视图处理部分,而是调用适合的HttpMessageConverter,将返回值写入输出流。

    在传日期格式的数据到前台的时候,fastjson默认将Date类型转为Long型,所以会导致后台Date类型的数传到前台出错
    解决办法:
    1.局部解决-加注解。即在相应的字段上加入如下注解@JSONField (format="yyyy-MM-dd HH:mm:ss"),fastjson向前台输出json时,就会保留你设置的格式。但是这样的话,就是你要注意,在每个Date类型的字段上都要加上这样的注解
    2.全局解决-写一个注解的处理类,在xml文件里调用自己定义的一个class,相当于重写fastjson的converter。
    3.全局解决-写一个Date和String转换类,在后台先将数据转成String再传到前台去。前台string传过来之后再转成Date,这样就不会出错

  • 相关阅读:
    howtoautomateyouriphoneappbuildswithhudson
    buildingiphoneappswithhudsonpart2
    Linux常用命令全集
    介绍
    Linux文件查找命令find,xargs详述
    Tomcat for Mac OS
    Jenkins在Mac平台安裝
    Linux下的shell与make
    buildingiosappsforovertheairadhocdistribution
    linux下u盘的使用
  • 原文地址:https://www.cnblogs.com/downey/p/4928978.html
Copyright © 2011-2022 走看看