Spring mvc 接收json对象

前端技术 2023/09/03 JavaScript

本文通过代码实例介绍spring mvc 接收json数据的方法,具体详情如下所示:

接收JSON

使用 @RequestBody 注解前台只需要向 Controller 提交一段符合格式的 JSON,Spring 会自动将其拼装成 bean。

1)在上面的项目中使用第一种方式处理返回JSON的基础上,增加如下方法:

Java代码

  @RequestMapping(value=\"/add\",method=RequestMethod.POST, headers = {\"content-type=application/json\",\"content-type=application/xml\"}) 
  @ResponseBody 
  public Object addUser(@RequestBody User user) 
  { 
    System.out.println(user.getName() + \" \" + user.getAge()); 
    return new HashMap<String, String>().put(\"success\", \"true\"); 
  } 

这里的POJO如下:

Java代码

  public class User { 
    private String name; 
    private String age; 
    //getter setter 
  } 

2)而在前台,我们可以用 jQuery 来处理 JSON。从这里,我得到了一个 jQuery 的插件,可以将一个表单的数据返回成JSON对象:

Js代码

 $.fn.serializeObject = function(){ 
    var o = {}; 
    var a = this.serializeArray(); 
    $.each(a, function(){ 
      if (o[this.name]) { 
        if (!o[this.name].push) { 
          o[this.name] = [o[this.name]]; 
        } 
        o[this.name].push(this.value || \'\'); 
      } 
      else { 
        o[this.name] = this.value || \'\'; 
      } 
    }); 
    return o; 
  }; 

   以下是使用 jQuery 接收、发送 JSON 的代码:

Js代码

$(document).ready(function(){ 
    jQuery.ajax({ 
      type: \'GET\', 
      contentType: \'application/json\', 
      url: \'jsonfeed.do\', 
      dataType: \'json\', 
      success: function(data){ 
        if (data && data.status == \"0\") { 
          $.each(data.data, function(i, item){ 
            $(\'#info\').append(\"姓名:\" + item.name +\",年龄:\" +item.age); 
          }); 
        } 
      }, 
      error: function(){ 
        alert(\"error\") 
      } 
    }); 
    $(\"#submit\").click(function(){ 
      var jsonuserinfo = $.toJSON($(\'#form\').serializeObject()); 
      jQuery.ajax({ 
        type: \'POST\', 
        contentType: \'application/json\', 
        url: \'add.do\', 
        data: jsonuserinfo, 
        dataType: \'json\', 
        success: function(data){ 
          alert(\"新增成功!\"); 
        }, 
        error: function(){ 
          alert(\"error\") 
        } 
      }); 
    }); 
  }); 

但是似乎用Spring这套东西真是个麻烦的事情,相对Jersey对RESTful的实现来看,确实有很多不简洁的地方。

以上所述是本文给大家分享的Spring mvc 接收json数据的相关资料,希望大家喜欢。

本文地址:https://www.stayed.cn/item/6508

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。