在項目開發中,接口與接口之間,前后端之間數據的傳輸都使用Json格式,在 Spring Boot 中,接口返回Json格式的數據很簡單,在 Controller 中使用@RestController注解即可返回 Json 格式的數據。
Spring Boot 中默認使用的 JSON 解析框架是 Jackson。
在實際項目中,常用的數據結構無非有類對象、List 對象、Map 對象
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.json</groupId>
<artifactId>RebackJson</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<!-- 聲明項目配置依賴編碼格式為 utf-8 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<fastjson.version>1.2.24</fastjson.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.tszr.json.user;
public class User {
private int id;
private String name;
private String password;
public User(int id, String name, String password) {
// TODO Auto-generated constructor stub
this.id = id;
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.tszr.json.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tszr.json.user.User;
@RestController
@RequestMapping("/json")
public class UserController {
@RequestMapping("/user")
public User getUser() {
return new User(10, "貝西", "11");
}
@RequestMapping("/list")
public List<User> getUserList() {
List<User> userlist = new ArrayList<>();
User user1 = new User(1, "吳裕雄", "123456");
User user2 = new User(1, "天生自然", "123456");
userlist.add(user1);
userlist.add(user2);
return userlist;
}
@RequestMapping("/map")
public Map<String, Object> getMap() {
Map<String, Object> map = new HashMap<>(3);
User user3 = new User(1, "天生自然", "123456");
map.put("作者信息", user3);
map.put("博客地址", "https://www.cnblogs.com/tszr");
map.put("公眾號", "貝西奇談");
map.put("B站", "貝西貝西");
return map;
}
}
package com.tszr.json;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan
@SpringBootApplication
public class JsonApplication {
public static void main(String[] args) {
SpringApplication.run(JsonApplication.class, args);
}
}

Jackson 中對 null 的處理
在實際項目中,我們難免會遇到一些 null 值。當我們轉 JSON 時,不希望這些 null 出 現,比如我們希望所有的 null 在轉 JSON 時都變成空字符串。
在 Spring Boot 中,我們做一下配置即可,新建一個 Jackson 的配置類:
package com.tszr.json.configuration;
import java.io.IOException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
@Configuration
public class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeString("");
}
});
return objectMapper;
}
}
