使用@ResponseBody物件轉json和@RequestBody進行json轉物件案例

水巷石子發表於2020-10-14
  • (1)什麼時候使用到json?
    ajax請求

  • (2)javaBean對像與json互轉 如阿里巴巴的fastjson

  • (3)返回值轉json @ResponseBody
    註解加在方法上,SpringMVC可以自動將方法的返回物件轉為json,傳送給頁面

  • (4)引數轉json @RequestBody
    在形參的前邊加上@RequestBody註解,該註解可以自動解析頁面傳送過來的json資料,解析完之後,自動的將json中的資料封裝到形參物件

案例程式碼

pom.xml

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.2.6.RELEASE</version>
            </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.74</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.3</version>
        </dependency>

    </dependencies>

首先是阿里巴巴的fastjson的測試程式碼:

/**
 * Created by 李柏霖
 * 2020/10/14 23:26
 */

package com.lbl.person;

import com.alibaba.fastjson.JSON;
import com.lbl.domain.Person;
import org.junit.Test;

public class TestPersnoToJson {
        @Test
        public void  test01(){
            Person p = new Person("jack","1234");
            String json  =  JSON.toJSONString(p);//呼叫靜態方法toJSONString,引數傳入物件 ,將物件轉成json
            System.out.println(json);
        }
        @Test
        public void  test02(){
            String json = "{\"username\":\"jack\",\"password\":\"`123456`\"}";
            Person p = JSON.parseObject(json,Person.class);//json轉javaBean,參1,json  參2 類
            System.out.println(p);
        }
    }

執行效果:

在這裡插入圖片描述

然後是@ResponseBody和@RequestBody進行json的轉換程式碼案例

PersonController

/**
 * Created by 李柏霖
 * 2020/10/13 10:18
 */

package com.lbl.Controller;

import com.lbl.domain.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
public class PersonController {
    @ResponseBody
    @RequestMapping(path = "demo05.action",method = {RequestMethod.POST,RequestMethod.GET})//回顯頁面
    public  Object test05(){//

        Person p1 = new Person("jack","1234");
        Person p2 = new Person("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;
    }




}

Person

/**
 * Created by 李柏霖
 * 2020/10/13 9:47
 */

package com.lbl.domain;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
    private String username;
    private String password;
}

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="com.lbl.Controller"></context:component-scan>

    <!---->
    <mvc:annotation-driven/>
    <!--配置檢視解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--定義頁面路徑的字首-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--定義頁面路徑的字尾-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>

</web-app>

執行效果:

在這裡插入圖片描述

用postman訪問:

在這裡插入圖片描述

在這裡插入圖片描述

相關文章