SoFunction
Updated on 2025-03-09

Spring mvc receives json object

This article introduces the method of spring mvc receiving json data through code examples. The specific details are as follows:

Receive JSON

Using the @RequestBody annotation front desk only needs to submit a format-compliant JSON to the Controller, and Spring will automatically assemble it into beans.

1) In the above project, use the first method to process the return JSON, add the following method:

Java code

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

The POJO here is as follows:

Java code

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

2) And in the foreground, we can use jQuery to handle JSON. From here, I get a jQuery plugin that can return the data of a form to a JSON object:

Js code

 $. = function(){ 
    var o = {}; 
    var a = (); 
    $.each(a, function(){ 
      if (o[]) { 
        if (!o[].push) { 
          o[] = [o[]]; 
        } 
        o[].push( || ''); 
      } 
      else { 
        o[] =  || ''; 
      } 
    }); 
    return o; 
  }; 

The following is the code to receive and send JSON using jQuery:

Js code

$(document).ready(function(){ 
    ({ 
      type: 'GET', 
      contentType: 'application/json', 
      url: '', 
      dataType: 'json', 
      success: function(data){ 
        if (data &amp;&amp;  == "0") { 
          $.each(, function(i, item){ 
            $('#info').append("Name: " + +", Age: " +);          }); 
        } 
      }, 
      error: function(){ 
        alert("error") 
      } 
    }); 
    $("#submit").click(function(){ 
      var jsonuserinfo = $.toJSON($('#form').serializeObject()); 
      ({ 
        type: 'POST', 
        contentType: 'application/json', 
        url: '', 
        data: jsonuserinfo, 
        dataType: 'json', 
        success: function(data){ 
          alert("New addition was successful!"); 
        }, 
        error: function(){ 
          alert("error") 
        } 
      }); 
    }); 
  }); 

But it seems that using Spring is really a troublesome thing. Compared with Jersey's implementation of RESTful, there are indeed many things that are not concise.

The above is the relevant information about Spring mvc receiving json data shared by this article. I hope you like it.