Java receives json parameters

JSON is not the only way to transmit data on the Internet, there is also an XML format. JSON and XML can perform many of the same tasks, so why should we use JSON instead of XML?

The main reason to use JSON is JavaScript. As we all know, JavaScript is one of the indispensable technologies in web development, and JSON is based on a subset of JavaScript. JavaScript supports JSON by default, and as long as you learn JavaScript, you can easily use JSON without learning additional Knowledge.

Another reason is that JSON is more readable than XML, and JSON is more concise and easier to understand.

Compared to XML, JSON has the following advantages:

1. Simple and compact structure: Compared with XML, JSON follows a simple and compact style, which is conducive to programmers editing and reading, while XML is relatively complex;

2. Faster: JSON is faster to parse than XML (because XML is very similar to HTML, and extra memory is consumed when parsing large XML files). JSON format takes up less storage space to store the same data;

3. High readability: The structure of JSON is conducive to programmers' reading.

Java receives json parameters

/*
 * 第一种:以RequestParam接收
 * http://localhost:8080/test1?id=1
 * */
@RequestMapping(value = "/test1",method=RequestMethod.GET)
public void test1(@RequestParam("id") String id){
    System.out.println("id:"+id);    
}

/*
 * 第二种:以实体类接收
 * {"username": "zhangsan","id":"2"}
 * */
@RequestMapping(value = "/test2",method=RequestMethod.POST)
public void test1(@RequestBody User user) throws Exception{
    System.out.println("username:"+user.getUsername());    
}

/*
 * 第三种:以Map接收
 * {"username": "zhangsan","id":"2"}
 * */
@RequestMapping(value = "/test3",method=RequestMethod.POST)
public void test3(@RequestBody Map<String, String> map) throws Exception{
    System.out.println("username:"+map.get("username"));    
}

/*
 * 第四种:以List接收
 * [{"username": "zhangsan","id":"2"},{"username": "lisi","id":"1"}]
 * */
@RequestMapping(value = "/test4",method=RequestMethod.POST)
public void test4(@RequestBody List<User> list) throws Exception{
    for(User user:list){
        System.out.println("username:"+user.getUsername());
    }
}

/*
 * 第五种:以JSON对象接收
 * {"username": "zhangsan","id":"2","role":{"rolename":"admin"}}
 * */
@RequestMapping(value = "/test5",method=RequestMethod.POST)
public void test5(@RequestBody JSONObject json) throws Exception{
    System.out.println("username:"+json.getString("username"));    
    System.out.println("rolename:"+json.getJSONObject("role").getString("rolename"));
}}

If reprinted, please indicate the source: Open Source Byte https://sourcebyte.vip/article/324.html

Guess you like

Origin blog.csdn.net/qq_35634154/article/details/132508623