springMVC學習總結(四)springmvc處理json數據類型以及fastjson的使用


springMVC學習總結(四)springmvc處理json數據類型以及fastjson的使用

主要內容:
這篇文章主要是總結之前使用springmv接收json的時候遇到的問題,下面通過前台發送ajax數據后天springmvc接收,總結springmvc接收並處理ajax的問題。

注意點:
1、前台發送ajax數據時必須設置的屬性:
contentType='application/json' 如果不設置,后台獲取到的將是url編碼的文本,該屬性是指定發送的數據的類型為json。
2、本文后台使用fastjson解析json

一、后台接收json數據以及fastjson的使用:

json對象

jsp

function fun(){
    $.ajax({
        url:'/testAjax.action',
        data:"{'name':'xujie','age':'25'}",
        type:'POST',
        dataType:'json',
        contentType:'application/json'
    })
}

contentType:'application/json' //告訴服務器我發送的是json格式數據
dataType:'json',//告訴服務器,我要接收的是json格式數據

Controller

直接獲取對象中的屬性

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

封裝到某個pojo中:

@RequestMapping(value = "/testAjax.action",method = RequestMethod.POST)
@ResponseBody
public String testAjax(@RequestBody String jsonstr){
    Person person = JSONObject.parseObject(jsonstr, Person.class);//將json字符串轉換成json對象
    System.out.println(person);
    return "200";
}

輸出

json數組

Controller

@RequestMapping(value = "testAjax.action",method = RequestMethod.POST)
public void testAjax(@RequestBody String jsonstr){
    JSONArray array = JSONObject.parseArray(jsonstr);
    JSONObject jsonObject = JSONObject.parseObject(array.get(0).toString());
    String name = (String) jsonObject.get("name");
    System.out.println(name); //獲取到了第一個對象的name

}

jsp

function fun(){
    $.ajax({
        url:'/testAjax.action',
        data:"[{'name':'xujie','age':'25'},{'name':'yuanxiliu','age':'20'}]",
        type:'POST',
        dataType:'json',
        contentType:'application/json'
    })
}

輸出

二、后台發送json數據:

1、通過springmvc的注解@ResponseBody 示例:

List/map
Controller

@RequestMapping(value = "testAjax.action",method = RequestMethod.POST)
@ResponseBody
public ArrayList<String> testRequestBody() {
	//這里以list為例,map跟這個一樣的
    ArrayList<String> list = new ArrayList<String>();   
    list.add("apple");
    list.add("orange");
    list.add("pea");
    return list;
}

jsp

function fun(){
    $.ajax({
        type : "post",
        dataType : "json",
        url : "/testAjax.action",
        success : function(result) {
            alert(JSON.stringify(result));
        }
    });
}

要點:
在我做這篇總結的時候,一直忘了一個事,導致使用@ResponseBody返回的時候,前台一直報錯:406 (Not Acceptable) 最終發現如果使用@ResponseBody必須要添加jackson的依賴,因為springmvc在做返回的時候通過jackson去判斷返回什么類型,我這里用的maven所以添加依賴:

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
</dependency>

2、通過httpServletResponse的writer返回:

list:

Controller

@RequestMapping(value = "testAjax.action",method = RequestMethod.POST)
public void testAjax(HttpServletResponse response){
    ArrayList<String> list = new ArrayList<String>();
    list.add("apple");
    list.add("orange");
    list.add("pea");
    String jsonlist = JSON.toJSONString(list);
	response.getWriter().write(jsonlist);
    
}

jsp

function fun(){
    $.ajax({
        url:'/testAjax.action',
        type:'POST',
        dataType:'json',
        contentType:'application/json',
        success:function(data){
            alert(JSON.stringify(data));
        }
    })
}

map:

Controller

@RequestMapping(value = "testAjax.action",method = RequestMethod.POST)
public void testAjax(HttpServletResponse response){
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("name","xujie");
    map.put("age","23");
    String jsonlist = JSON.toJSONString(map);
    response.getWriter().write(jsonlist);
} 

jsp

function fun(){
    $.ajax({
        url:'/testAjax.action',
        type:'POST',
        dataType:'json',
        contentType:'application/json',
        success:function(data){
            alert(JSON.stringify(data));
        }
    })
}

對象

@RequestMapping(value = "testAjax.action",method = RequestMethod.POST)
@ResponseBody
public void testAjax(HttpServletResponse response) throws Exception {
    Person person = new Person();
    person.setAge("23");
    person.setName("xujie");
    String string = JSON.toJSONString(person);
    response.getWriter().write(string);
}

jsp

function fun(){
    $.ajax({
        url:'/testAjax.action',
        type:'POST',
        dataType:'json',
        contentType:'application/json',
        success:function(data){
            alert(JSON.stringify(data));
        }
    })
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM