Day25SSM's SpringMVC return value type is Object json processing

The return value of the processor-json data processing

  • (1) When will json be used?
    Ajax request
  • (2) Convert between javaBean object and json such as阿里巴巴的fastjson
  • (3) The return value to json @ResponseBody
    annotation is added to the method, and SpringMVC can automatically convert the return object of the method to json and send it to the page
  • (4) Parameter to json is @RequestBody
    annotated with @RequestBody in front of the formal parameter. This annotation can automatically parse the json data sent from the page. After parsing, the data in the json is automatically encapsulated into the formal parameter object

pom.xml

     <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.74</version>
      </dependency>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
      </dependency>

TestPersnoToJson

public class TestPersnoToJson {
    
    
    @Test
    public void  test01(){
    
    
        Person p = new Person(1,"jack","1234");
        String json  =  JSON.toJSONString(p);//调用静态方法toJSONString,参数传入对象 ,将对象转成json
        System.out.println(json);
    }
    @Test
    public void  test02(){
    
    
        String json = "{\"id\":1,\"password\":\"1234\",\"username\":\"jack\"}";
        Person p = JSON.parseObject(json,Person.class);//json转javaBean,参1,json  参2 类
        System.out.println(p);
    }
}

pom.xml

Depends on jackson library

  <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.11.3</version>
      </dependency>

Demo02ReturnController

 @RequestMapping(path = "demo05.action",method = {
    
    RequestMethod.POST,RequestMethod.GET})//回显页面
    public @ResponseBody Object test05(){
    
    //

        Person p1 = new Person(1,"jack","1234");
        Person p2 = new Person(2,"rose","1234");
        List<Person> list = new ArrayList<Person>();
        list.add(p1);
        list.add(p2);
        return list; //springmvc将 list使用ObjectMapper转成json
    }
    @RequestMapping(path = "demo06.action",method = {
    
    RequestMethod.POST,RequestMethod.GET})//回显页面
    public ModelAndView  test06(@RequestBody  Person person){
    
    //
        System.out.println("object:"+person);
       return null;
    }

PostMan

Insert picture description here

Guess you like

Origin blog.csdn.net/u013621398/article/details/109073153