• 认真地记录技术中遇到的坑!
  • 能摸鱼真是太好啦!嘿嘿嘿!

SpringMVC JSON处理

Java 悠悠 7年前 (2017-11-01) 4173次浏览 0个评论

JSON 作为非常轻便的数据交互格式,在Spring中用的非常多,作为客户端和服务端数据交互的数据格式。

使用@ResponseBody返回JSON数据

如果需要使得某个服务端的接口返回个客户端JSON格式的数据,可以通过给Controller添加 @ResponseBody 注解实现。

该方法不需要额外的配置,只需要使用 @ResponseBody 注解,并且手动把返回值进行 JSON 序列化即可。

@RequestMapping(value = "/getData",  // 匹配路由
      method = RequestMethod.GET,  // 匹配请求方法
      produces = "text/json;charset=UTF-8")  // 设置返回值的 content-type 为 json
@ResponseBody
public String getData() {
    HashMap<String, Object> result = new HashMap<String, Object>();
    return JSON.toJSONString(result); // 返回JSON格式字符串
}

利用HttpServletResponse返回JSON数据

这种方法通过在 Controller 中获取 HttpServletResponse 对象实例,然后使用 response.getOutputStream() 或 response.getWriter() 直接把JSON格式字符串写入返回 Body 中即可:

public String getData(HttpServletResponse response) {
    response.setCharacterEncoding("utf-8");  //防止ajax接受到的中文信息乱码  
    out = response.getWriter();
    HashMap<String, Object> result = new HashMap<String, Object>();
    out.print(JSON.toJSONString(result));  // 将 JSON 字符串写入返回Body
}

使用@RequestBody处理JSON请求数据

有时候,服务端接受到的参数为客户端通过 POST 提交的 JSON 格式数据,对于这类数据,需要使用 @RequestBody 注解进行处理:

@RequestMapping(value = "/postData",  // 匹配路由
      method = RequestMethod.POST,  // 匹配请求方法
      produces = "text/json;charset=UTF-8")  // 设置返回值的 content-type 为 json
@ResponseBody
public String postData(@RequestBody postData) {
    System.out.println("post data:" + postData);
    JSONObject dataJson = JSONObject.parse(postData);  // 反序列化 JSON 字符串得到 JSONObject 对象
}

修改Spring配置文件添加JSON解析

可用于在Spring Controller中使用FastJson进行数据的Serialize and Deserialize。

由于使用了 fastjson 需要导入,相关的 JSON 序列化自定义化设置参考:JSON格式处理-fastjson

FastJsonConfig配置如下:

<bean id="fastJsonConfig" class="com.alibaba.fastjson.support.config.FastJsonConfig">
    <!-- Default charset -->
    <property name="charset" value="UTF-8" />
    <!-- Default dateFormat -->
    <property name="dateFormat" value="yyyy-MM-dd HH:mm:ss" />
    <!-- Feature -->
    <property name="features">
        <list>
            <value>Your feature</value>
            <value>Your feature</value>
        </list>
    </property>
    <!-- SerializerFeature -->
    <property name="serializerFeatures">
        <list>
            <value>Your serializer feature</value>
        </list>
    </property>
    <!-- Global SerializeFilter -->
    <property name="serializeFilters">
        <list>
            <ref bean="Your serializer filter"/>    
        </list>
    </property>
    <!-- Class Level SerializeFilter -->
    <property name="classSerializeFilters">
        <map>
            <entry key="Your filter class" value-ref="Your serializer filter"/>
        </map>
    </property>
</bean>

HttpMessageConverter配置如下:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
            <!-- MediaTypes -->
            <property name="supportedMediaTypes">
                <list>
                    <value>application/json</value>
                </list>
            </property>
            <!-- FastJsonConfig -->
            <property name="fastJsonConfig" ref="fastJsonConfig" />
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

<mvc:default-servlet-handler />

转载请注明出处 SpringMVC JSON处理
喜欢 (2)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址