SpringMVC中使用JSON

前臺發送:

  • 傳遞JSON對象
function requestJson(){
    $.ajax.({
        type : 「post」,
        url : 「${pageContext.request.contextPath}/testJson/responseJson」,
        contextType : 「application/x-www-form-urlencoded;charset=utf-8」,//默認值
        data : ‘{「username」 : 「name 「, 「gender」 : 「male」}’,
        dataType : 「json」,
        success:function(data){
    console.log(「服務器處理過的用戶名是:」  + data.username);
    console.log(「服務器處理過的性別是:」 + data.gender);
}
});
}
  • 傳送JSON字符串
function requestJson(){
    var json = {「username」 : 「name 「, 「gender」 : 「male」};
    var jsonstr = JSON.stringify(json);//json對象轉換json字符串
    $.ajax.({
        type : 「post」,
        url : 「${pageContext.request.contextPath}/testJson/responseJson」,
        contextType : 「application/json;charset=utf-8’
traditional:true,//這使json格式的字符不會被轉碼,
        data : jsonstr,
        dataType : 「json」,
        success:function(data){
            console.log(「服務器處理過的用戶名是:」  + data.username);
            console.log(「服務器處理過的性別是:」 + data.gender);
        }
    });
}

下面介紹以上參數的含義:
type:Http請求的方式,通常使用POST和GET
url:請求的url地址,也就是咱們所要請求的Controller的地址
contextType:這裏要注意,若是使用的是key/value值,那麼這個請求的類型應該是application/x-www-form-urlencoded/charset=utf-8,該值也是默認值。
若是是JSON格式的話應該是application/json;charset=utf-8
traditional:若一個key是個數組,即有多個參數的話,能夠把該屬性設置爲true,這樣就能夠在後臺能夠獲取到這多個參數。
data:要發送的JSON字符串
success:請求成功以後的回調函數
error:請求失敗以後的回調函數javascript

SpringMVC須要的jar包:jackson-core-asl-x.x.xx.jar、jackson-mapper-asl-x.x.xx.jar
SpringMVC配置文件中添加:java

後臺接收

  • 接收JSON對象
    Controller控制器中的方法
    ①直接獲取就行
@RequestMapping("/requestJson")
public @ResponseBody Person requestJson(Person p) {
System.out.println("json傳來的串是:" + p.getGender() + " " + p.getUserName() + " " +p.isAdalt());
p.setUserName(p.getUserName().toUpperCase());
return p;
}
Person的實體類:
public class Person {
    private String userName;
    private String gender;
    private boolean adalt;
}
  • 接收JSON字符串
@RequestBody(接收的是JSON的字符串而非JSON對象),註解將JSON字符串轉成JavaBean
@ResponseBody註解,將JavaBean轉爲JSON字符串,返回到客戶端。具體用於將Controller類中方法返回的對象,經過HttpMessageConverter接口轉換爲指定格式的數據,好比JSON和XML等,經過Response響應給客戶端。produces=」text/plain;charset=utf-8」設置返回值。
②把JSON字符串發送過來,使用註解@RequestBody接收String字符串以後,再解析出來
@RequestMapping(value = "testAjax.action",method = RequestMethod.POST) 
public void testAjax(@RequestBody String jsonstr){ 
JSONObject jsonObject = JSONObject.parseObject(jsonstr);//將json字符串轉換成json對象 String age = (String) jsonObject.get("age");//獲取屬性 
System.out.println(age); 
}

③固然也能夠使用Map集合
@RequestMapping("/jsontest")
public void test(@RequestBody Map map){
    String username = map.get("username").toString();
    String password = map.get("password").toString();
}
相關文章
相關標籤/搜索