Spring MVC学习05--JSON序列化

修改pom文件,添加jackson的依赖:

<!-- Spring MVC默认使用jackson作为JSON处理方式 -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

 

修改User类,添加一些Jackson的注解:

 1 package com.yas.entity;
 2 
 3 import com.fasterxml.jackson.annotation.JsonFormat;
 4 import com.fasterxml.jackson.annotation.JsonIgnore;
 5 import com.fasterxml.jackson.annotation.JsonInclude;
 6 import com.fasterxml.jackson.annotation.JsonProperty;
 7 import com.fasterxml.jackson.databind.annotation.JsonSerialize;
 8 import com.yas.serialize.MySerializer;
 9 
10 import java.util.Date;
11 
12 public class User {
13     //json序列化时的名称
14     @JsonProperty("id2")
15     private Integer id;
16 
17     //如果为空,则不转化
18     @JsonInclude(JsonInclude.Include.NON_NULL)
19     private String name;
20 
21     //忽略此属性
22     @JsonIgnore
23     private Boolean gender;
24 
25     @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
26     private Date birth;
27 
28     //自定义格式化
29     @JsonSerialize(using = MySerializer.class)
30     private Double salary = 10000.126;
31 
32 
33     public User() {
34     }
35 
36     public User(Integer id, String name, Boolean gender, Date birth) {
37         this.id = id;
38         this.name = name;
39         this.gender = gender;
40         this.birth = birth;
41     }
42 
43     public Integer getId() {
44         return id;
45     }
46 
47     public void setId(Integer id) {
48         this.id = id;
49     }
50 
51     public String getName() {
52         return name;
53     }
54 
55     public void setName(String name) {
56         this.name = name;
57     }
58 
59     public Boolean getGender() {
60         return gender;
61     }
62 
63     public void setGender(Boolean gender) {
64         this.gender = gender;
65     }
66 
67     public Date getBirth() {
68         return birth;
69     }
70 
71     public void setBirth(Date birth) {
72         this.birth = birth;
73     }
74 
75     @Override
76     public String toString() {
77         return "User{" +
78                 "id=" + id +
79                 ", name='" + name + '\'' +
80                 ", gender=" + gender +
81                 ", birth=" + birth +
82                 '}';
83     }
84 }

 

添加用于自定义格式化的类:

 1 package com.yas.serialize;
 2 
 3 import com.fasterxml.jackson.core.JsonGenerator;
 4 import com.fasterxml.jackson.databind.JsonSerializer;
 5 import com.fasterxml.jackson.databind.SerializerProvider;
 6 
 7 import java.io.IOException;
 8 import java.math.BigDecimal;
 9 
10 public class MySerializer extends JsonSerializer<Double> {
11 
12     @Override
13     public void serialize(Double aDouble, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
14         String number = BigDecimal.valueOf(aDouble).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
15         jsonGenerator.writeNumber(number);
16     }
17 }

 

添加测试用的Controller:

 1 package com.yas.controller;
 2 
 3 import com.yas.entity.User;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.web.bind.annotation.RequestBody;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.ResponseBody;
 8 
 9 import java.util.ArrayList;
10 import java.util.Date;
11 import java.util.List;
12 
13 @Controller
14 @RequestMapping("/json")
15 public class JsonController {
16 
17     @ResponseBody
18     @RequestMapping("/test1")
19     public User test1(){
20         User user = new User(1,"zhangsan",true,new Date());
21         return user;
22     }
23 
24     @ResponseBody
25     @RequestMapping("/test2")
26     public List<User> test2(){
27         User user1 = new User(1,"zhangsan",true,new Date());
28         User user2 = new User(2,"lisi",true,new Date());
29         List<User> users = new ArrayList<User>();
30         users.add(user1);
31         users.add(user2);
32         return users;
33     }
34 
35     @ResponseBody
36     @RequestMapping(value = "/test3",produces = "text/html;charset=utf-8")
37     public String test3(){
38         return "你好aaa";
39     }
40 
41     @ResponseBody
42     @RequestMapping("/test4")
43     public String test4(@RequestBody User user){
44         //@RequestBody 从json字符串封装到User对象中,只支持post提交
45         System.out.println(user.getId());
46         System.out.println(user.getName());
47         return "ok";
48     }
49 }

 

添加jsp页面

<%--
  Created by IntelliJ IDEA.
  User: yanga
  Date: 2021/10/26
  Time: 15:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Title</title>
  <script src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
  <script type="text/javascript">
    $(function (){
      $("#btn").click(function (){
        let user = {id:1,name:"张三"};
        let userJson = JSON.stringify(user);
        $.ajax({
          url:"${pageContext.request.contextPath}/json/test4",
          type:"post",
          data:userJson,
          contentType:"application/json",
          success:function (d){
            console.log(d);
          }
        });
      });
    });

  </script>
</head>
<body>
  <input type="button" value="发送json" id="btn"">
</body>
</html>

 

上一篇:@JsonFormat与@DateTimeFormat注解的使用


下一篇:问题篇-优化时间注解