Spring MVC 之 json格式的输入和输出

来源:互联网 发布:图书录入软件 编辑:程序博客网 时间:2024/06/05 08:46

Spring mvc处理json需要使用jackson的类库,因此为支持json格式的输入输出需要先修改pom.xml增加jackson包的引用

<!-- json--><dependency>    <groupId>org.codehaus.jackson</groupId>    <artifactId>jackson-core-lgpl</artifactId>    <version>1.8.1</version></dependency><dependency>    <groupId>org.codehaus.jackson</groupId>    <artifactId>jackson-mapper-lgpl</artifactId>    <version>1.8.1</version></dependency>

 

在Jsp请求页面中,增加客户端json格式的数据输入。

var cfg = {                  type: 'POST',                  data: JSON.stringify({userName:'winzip',password:'password',mobileNO:'13818881888'}),                  dataType: 'json',                  contentType:'application/json;charset=UTF-8',                          success: function(result) {                 alert(result.success);             }   };function doTestJson(actionName){         cfg.url = actionName;         $.ajax(cfg);}

spring mvc中解析输入为json格式的数据有两种方式

1:使用@RequestBody来设置输入

@RequestMapping("/json1")   @ResponseBody   public JsonResult testJson1(@RequestBody User u){             log.info("get json input from request body annotation");             log.info(u.getUserName());             return new JsonResult(true,"return ok");}

2:使用HttpEntity来实现输入绑定

@RequestMapping("/json2")public ResponseEntity<JsonResult> testJson2(HttpEntity<User> u) {      log.info("get json input from HttpEntity annotation");      log.info(u.getBody().getUserName());      ResponseEntity<JsonResult> responseResult = new ResponseEntity<JsonResult>(                 new JsonResult(true, "return ok"), HttpStatus.OK);      return responseResult;}

Json格式的输出也对应有两种方式

1:使用@responseBody来设置输出内容为context body

2:返回值设置为ResponseEntity<?>类型,以返回context body ,另外第二种方式是使用ContentNegotiatingViewResolver来设置输出为json格式,需要修改servletcontext配置文件如下

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">      <property name="order" value="1" />      <property name="mediaTypes">           <map>                 <entry key="json" value="application/json" />           </map>      </property>      <property name="defaultViews">           <list>                 <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />           </list>      </property>      <property name="ignoreAcceptHeader" value="true" /></bean>

但这种格式的输出会返回{model类名:{内容}} 的json格式, 例如,以下代码

@RequestMapping("/json3.json")public JsonResult testJson3(@RequestBody User u) {      log.info("handle json output from ContentNegotiatingViewResolver");      return new JsonResult(true, "return ok");}

期望的返回是 {success:true,message:”return ok”}; 但实际返回的却是

{"jsonResult":{"success":true,"msg":"return ok"}} 原因是MappingJacksonJsonView中对返回值的处理未考虑modelMap中只有一个值的情况,直接是按照mapName:{mapResult}的格式来返回数据的。 修改方法,重载MappingJacksonJsonView类并重写filterModel方法如下

protected Object filterModel(Map<String, Object> model) {      Map<?, ?> result = (Map<?, ?>) super.filterModel(model);      if (result.size() == 1) {           return result.values().iterator().next();      } else {           return result;      }}

对应的ContentNegotiatingViewResolver修改如下

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">         <property name="order" value="1" />         <property name="mediaTypes">                   <map>                            <entry key="json" value="application/json" />                   </map>         </property>         <property name="defaultViews">                   <list>                            <bean class="net.zhepu.json.MappingJacksonJsonView" />                   </list>         </property>         <property name="ignoreAcceptHeader" value="true" /></bean>
原创粉丝点击