Talk about the relationship between @ RequestBody and Json

  • 2021-09-11 20:15:00
  • OfStack

When using springmvc, the background @ RequestBody accepts a string in json format, and 1 is a string.

We can use @ RequestBody Map


    @RequestMapping(value="/queryAccountList.do",produces="application/json;charset=UTF-8")
    @ResponseBody
    public HashMap<String, Object> queryAccountList(@RequestBody Map<String, Object> paramsMap){
        System.out.println("paramsMap="+paramsMap);
        String  channel= (String) paramsMap.get("channel");
        String function_code=(String) paramsMap.get("function_code");
        Map<String, Object> reqParam=(Map<String, Object>)paramsMap.get("data");

When the front end calls our interface, the json string is passed in, which turns into an map object. This is mainly the underlying implementation of @ RequestBody, so we won't discuss it.

The difference between an json object and an json string:


var person={ " name " : " zhangsan " , " sex " : "Male" , " age " : " 24 " }//json Object 
var person='{ " name " : " zhangsan " , " sex " : "Male" , " age " : " 24 " }';//json String 

The json object is converted to an json string and the stringify method is called:


var person={"name":"zhangsan","sex":" Male ","age":"24"};//json Object 
var personString = JSON.stringify(person);
alert(personString);

SpringMVC Accepts json String Types

When developing based on REST in SpringMVC, a string in json format should be passed into the background from the front end instead of an json object

When GET and POST are raised, it is judged according to the values of request header Content-Type:

application/x-www-form-urlencoded, optional (i.e. not required, because the data in this case can also be processed by @ RequestParam, @ ModelAttribute, and of course @ RequestBody);

multipart/form-data, which cannot be processed (i.e. data in this format cannot be processed with @ RequestBody);

Other formats, must (other formats include application/json, application/xml, etc. Data in these formats must be processed using @ RequestBody).

@ RequestBody handles conversions between types and objects and json

1 @ RequestBody processing type

I often see the words @ RequestBody in controller in projects. What is his role?

1 When submitting data using forms, you can automatically encapsulate data into the corresponding Bean without using @ RequestBody. @ RequestBody is used to process Content-Type: application/json, application/xml and so on

It parses post data body by using HttpMessageConverters configured by HandlerAdapter and then binds to the corresponding bean.

Explanation: Using @ RequestBody to parse data requires adding jackson or fastjson dependency packages.

maven Introduces fastjson Package


<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.51</version>
</dependency>

2 object and json conversion to each other

You often encounter conversions between objects and json, conversions between public classes and json objects, and conversions between static inner classes and json objects in projects

2.1 Student class without inner class


@Data
public class Student {
    private String id;
    private String name;
    private int age;
    private String sex;
@Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}

json and object conversion


public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Student student = new Student();
        student.setName("good");
        String s = mapper.writeValueAsString(student);
        System.out.println(s);
        Student hd2 = mapper.readValue(s, Student.class);
        System.out.println(hd2);
    }

2.2 Student class with static inner class


@Data
public class Student {
    private String id;
    private String name;
    private int age;
    private String sex;
    private HomeData homeData;
    private BigDecimal salary;
    private String[] tel;
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
    @Data
    public static class HomeData{
        private Address address;
        @Override
        public String toString() {
            return ToStringBuilder.reflectionToString(this);
        }
        @Data
        public static class Address {
            private String country;
            private String city;
            @Override
            public String toString() {
                return ToStringBuilder.reflectionToString(this);
            }
        }
    }
}

Conversion between json and Objects


public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Student student = new Student();
        Student.HomeData homeData = new Student.HomeData();
        Student.HomeData.Address address = new Student.HomeData.Address();
        address.setCountry(" China ");
        address.setCity(" Shanghai ");
        homeData.setAddress(address);
        student.setHomeData(homeData);
        String s = mapper.writeValueAsString(address);
        System.out.println(s);
        Student.HomeData.Address hd2 = mapper.readValue(s, Student.HomeData.Address.class);
        System.out.println(hd2);
    }

Description: The main methods are mapper. writeValueAsString and mapper. readValue


Related articles: