zoukankan      html  css  js  c++  java
  • 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));
            }
        })
    }
  • 相关阅读:
    CMS之图片管理(4)
    CMS之图片管理(2)
    CMS:文章管理之控制器
    CMS:文章管理之视图(1)
    CMS:文章管理之视图(3)
    CMS:文章管理之视图(2)
    影响Incremental checkpoint position的条件
    oracle中一个数据文件的最大值(非lob)
    X$KCCLE
    图一时之快:手动释放Linux服务器内存
  • 原文地址:https://www.cnblogs.com/xujie09/p/8119130.html
Copyright © 2011-2022 走看看