為什么要使用json數(shù)據(jù)進(jìn)行交互
json數(shù)據(jù)格式在接口調(diào)用中 html頁面中比較常用,因?yàn)閖son格式比較簡(jiǎn)單,解析比較方便.
在Spring mvc 中客戶端請(qǐng)求時(shí),攜帶數(shù)據(jù)有兩種方式
第一中key/value
第二種json如下圖片
1.請(qǐng)求json返回json,要求請(qǐng)求的是json數(shù)據(jù),所以在前端頁面中需要將請(qǐng)求的內(nèi)容轉(zhuǎn)成json,不太方便.
2.請(qǐng)求 鍵值對(duì),輸出json.比較常用.
準(zhǔn)備環(huán)境
Spring Mvc通過 jackson包進(jìn)行json轉(zhuǎn)換.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0.pr3</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
JSON 測(cè)試
@Controller
@RequestMapping(value = "/test")
public class TestController{
@RequestMapping(value = "/testMethod", method = {RequestMethod.POST})
public @ResponseBody Test testMethod(@RequestBody Test test) {
return test;
}
}
這個(gè)代碼就是將我們的請(qǐng)求數(shù)據(jù),又給原封不動(dòng)的響應(yīng)回去.但是請(qǐng)求數(shù)據(jù)格式是json,而響應(yīng)數(shù)據(jù)也是json格式的.