json数据格式在接口调用中、html页面中较经常使用,json格式比较简单,解析还比较方便。html
<!-- json 转换--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.2</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency>
查看依赖树前端
[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.7.2:compile [INFO] | +- com.fasterxml.jackson.core:jackson-annotations:jar:2.7.0:compile [INFO] | \- com.fasterxml.jackson.core:jackson-core:jar:2.7.2:compile [INFO] \- org.codehaus.jackson:jackson-mapper-asl:jar:1.9.13:compile [INFO] \- org.codehaus.jackson:jackson-core-asl:jar:1.9.13:compile
在注解适配器中加入messageConverters
java
<!--注解适配器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> </list> </property> </bean>
注意:若是使用<mvc:annotation-driven/>
则不用定义上边的内容。jquery
使用jquery的ajax提交json串,对输出的json结果进行解析。web
//请求json,输出是json function requestJson(){ $.ajax({ type:'post', url:'${pageContext.request.contextPath }/requestJson.action', contentType:'application/json;charset=utf-8', //数据格式是json串,商品信息 data:'{"name":"手机","price":999}', //返回json结果 success:function(data){ alert(data); } }); }
@RequestMapping("/requestJson") public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom){ return itemsCustom; }
@RequestBody
将请求的商品信息的json串转成itemsCustom对象@ResponseBody
将itemsCustom转成json输出使用jquery的ajax提交key/value串,对输出的json结果进行解析ajax
//请求key/value,输出是json function responseJson(){ $.ajax({ type:'post', url:'${pageContext.request.contextPath }/responseJson.action', //请求是key/value这里不须要指定contentType,由于默认就 是key/value类型 //contentType:'application/json;charset=utf-8', //数据格式是json串,商品信息 data:'name=手机&price=999', //返回json结果 success:function(data){ alert(data.name); } }); }
@RequestMapping("/responseJson") public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom){ return itemsCustom; }