SpringMVC基于注解使用:JSON处理

目录

1、SpringMVC的返回JSON数据

2、SpringMVC的获取JSON数据

1、以@RequestBody接收

2、以实体类方式接收

3、以Map接收

4、以List接收


json数据格式回顾:

java转换为json 的过程一般会称为 “序列化”

json转换为java 的过程一般会称为 “反序列化”

Json的属和字符串值 必须要用双引号“” 不能用单引号

java

json

String

"xxx"

Integer

123

javaBean\Map

User

属性:id 、 name

{"id":1,"name":"xushu"}

数组、集合:

String[] \ List

["a","b","c"]

List

List

[

{"id":1,"name":"xushu"},

{"id":1,"name":"xushu"},

{"id":1,"name":"xushu"}

]

User

属性 id name Role role

{"id":1,"name":"xushu","role":{"id":1,"name":"管理员"}}

User

属性 id name List

{"id":1,"name":"xushu","role":[

{"id":1,"name":"管理员"}

{"id":2,"name":"普通员工"}

]}

 

1、SpringMVC的返回JSON数据

到目前为止我们编写的所有Controller的方法的返回值都是String类型,但是大家应该都知道,我们有时候数据传递特别是在ajax中,我们返回的数据经常需要使用json,那么如何来保证返回的数据的是json格式呢?

使用@ResponseBody注解

* ·响应json
* 1. 加入jackson依赖
* 2. 将jackson 的jar包加入WEB-INF的lib文件夹
* 3.在对应处理方法上面加上@ResponseBody用于标记该处理方法返回json
*      将@Controller改成@RestController
//@RestController   // 相当于控制器类中所有的处理方法都加上了@ResponseBody, 适用于web api

pom.xml

 <!--1.加入依赖-->
    <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.6.RELEASE</version>
    </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.10.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.10.3</version>
        </dependency>
    </dependencies>

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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
​
   <context:component-scan base-package="cn.tulingxueyuan"></context:component-scan>
​
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="prefix" value="/WEB-INF/page/"></property>
       <property name="suffix" value=".jsp"></property>
   </bean>
   <mvc:default-servlet-handler></mvc:default-servlet-handler>
   <mvc:annotation-driven></mvc:annotation-driven>
</beans>

JsonController.java


​
@Controller
public class JsonController {
​
   @ResponseBody
   @RequestMapping("/json")
   public List<User> json(){
       List<User> list = new ArrayList<User>();
       list.add(new User(1,"zhangsan",12,"男",new Date(),"1234@qq.com"));
       list.add(new User(2,"zhangsan2",12,"男",new Date(),"1234@qq.com"));
       list.add(new User(3,"zhangsan3",12,"男",new Date(),"1234@qq.com"));
       return list;
  }
}

User.java

public class User {
​
   private Integer id;
   private String name;
   private Integer age;
   private String gender;
   @JsonFormat( pattern = "yyyy-MM-dd")
   private Date birth;
   @JsonIgnore
   private String email;
​
   public User() {
  }
​
   public User(Integer id, String name, Integer age, String gender, Date birth, String email) {
       this.id = id;
       this.name = name;
       this.age = age;
       this.gender = gender;
       this.birth = birth;
       this.email = email;
  }
​
   public Integer getId() {
       return id;
  }
​
   public void setId(Integer id) {
       this.id = id;
  }
​
   public String getName() {
       return name;
  }
​
   public void setName(String name) {
       this.name = name;
  }
​
   public Integer getAge() {
       return age;
  }
​
   public void setAge(Integer age) {
       this.age = age;
  }
​
   public String getGender() {
       return gender;
  }
​
   public void setGender(String gender) {
       this.gender = gender;
  }
​
   public Date getBirth() {
       return birth;
  }
​
   public void setBirth(Date birth) {
       this.birth = birth;
  }
​
   public String getEmail() {
       return email;
  }
​
   public void setEmail(String email) {
       this.email = email;
  }
​
   @Override
   public String toString() {
       return "User{" +
               "id=" + id +
               ", name='" + name + '\'' +
               ", age=" + age +
               ", gender='" + gender + '\'' +
               ", birth=" + birth +
               ", email='" + email + '\'' +
               '}';
  }
}

同时@ResponseBody可以直接将返回的字符串数据作为响应内容

@Controller
public class OtherController {
   @ResponseBody
   @RequestMapping("/testResponseBody")
   public String testResponseBody(){
       return "<h1>success</h1>";
  }
}

@JsonIgnore    // 当返回javaBean 的json时 会忽略该属性
@JsonFormat(pattern = "yyyy-MM-dd")   // 用户转换json时格式化数据   JsonFormat和DateTimeFormat只需要设置一个可以了

2、SpringMVC的获取JSON数据

ajax我们经常用到,传的数据是json数据,json数据又有对象,数组。以下给大家总结了4种常用的获取json方式:

jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <script src="https://cdn.staticfile.org/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript">
      // 也没加载事件简写方式
      $(function(){

        $("#btnJson1").click(function(){
          $.ajax({
            url:"${pageContext.request.contextPath}/json/request01",
            method:"post",
            data:"张三",
            contentType:'application/json',
            dataType:"json",
            success:function(user){
              alert(user.name);
            }
          });
        });



        $("#btnJson2").click(function(){

          var user={'id':'1','name':'张三'};   // 定义js对象
          var jsonValue=JSON.stringify(user); // 对象转换为json字符串
          console.log(jsonValue)
          $.ajax({
            url:"${pageContext.request.contextPath}/json/request02",
            method:"post",
            data:'{"id":"1","name":"张三","birthady":"2019-01-01"}',
            contentType:'application/json',
            dataType:"json",
            success:function(user){
              alert(user.name);
            }
          });
        });


        $("#btnJson3").click(function(){

          $.ajax({
            url:"${pageContext.request.contextPath}/json/request03",
            method:"post",
            data:'{"idxx":"1","namexx":"张三","birthadyxx":"2019-01-01"}',
            contentType:'application/json',
            dataType:"json",
            success:function(user){
              alert(user.name);
            }
          });
        });


        $("#btnJson4").click(function(){
          var listUser=new Array();
          var user1={"id":"1","name":"张三","birthady":"2019-01-01"};
          var user2={"id":"2","name":"李四","birthady":"2019-01-01"};
          listUser.push(user1)
          listUser.push(user2)

          $.ajax({
            url:"${pageContext.request.contextPath}/json/request04",
            method:"put",
            //data:'[{"id":"1","name":"张三","birthady":"2019-01-01"},{"id":"2","name":"李四","birthady":"2019-01-01"}]',
            data:JSON.stringify(listUser),
            contentType:'application/json',
            dataType:"json",
            success:function(user){
              alert(user.name);
            }
          });
        });

      })

    </script>
  </head>
  <body>
<input type="button" value="发送单个参数的json数据" id="btnJson1"/><br/>
<input type="button" value="发送对象的json数据用javaBean接收" id="btnJson2"/><br/>
<input type="button" value="发送对象的json数据用Map接收" id="btnJson3"/><br/>
<input type="button" value="发送数组对象的json数据用List<User>接收" id="btnJson4"/><br/>
  </body>
</html>
* 请求Json接收
* 使用 @RequestBody,提前是一定要保证请求过来的参数数据一定json数据,并且内容类型也必须要是"application/json"

1、以@RequestBody接收

单个参数的json数据

@PostMapping("/json/request01")
@ResponseBody
public  User responseJson(@RequestBody String name){
    User user = new User(1, "徐庶","12346",new Date());
    System.out.println(name);
    return user;

}

2、以实体类方式接收

前端传来的是一个json对象时:{ id:1,name:xx},可以用实体类直接进行自动绑定

    @PostMapping(value="/json/request02",consumes = "application/json")
    @ResponseBody
    public  User requestJson02(@RequestBody User user){
        User user2 = new User(1, "fztx","12346",new Date());
        System.out.println(user);
        return user2;

    }

3、以Map接收

前端传来的是一个json对象时:{ id:1,name:xx},可以用Map来获取

    @PostMapping(value="/json/request03",consumes = "application/json")
    @ResponseBody
    public  User requestJson03(@RequestBody Map<String,String> map){
        User user2 = new User(1, "fztx","12346",new Date());
        System.out.println(map);
        return user2;

    }

4、以List接收

当前端传来这样一个json数组:[{ id:1,name:xx},{ id:1,name:xx},{ id:1,name:xx},...]时,用List接收

@PostMapping(value="/json/request04",consumes = "application/json")
@ResponseBody
public  User requestJson04(@RequestBody List<User> list){
    User user2 = new User(1, "fztx","12346",new Date());
    System.out.println(list);
    return user2;

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值