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; }