后端人员开发完毕后需要给前端提供访问的接口,并且返回相应的数据。
返回的数据格式多种多样,需要进行统一数据封装,方便前端人员使用。
boot导入web的启动包后,并不需要导jackson的相关包。
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
点开starter-web包,可以看到里面以及导入了jackson的相关包了
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jsonartifactId>
<version>2.3.7.RELEASEversion>
<scope>compilescope>
dependency>
starter-json包内以及封装了许多json需要用到的包,故不需要进行导包处理。
第二步,需要写一个配置类,配置相关信息。
@Configuration
public class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jsckonObjectMapper(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;
}
}
第三步,编写一个封装类,一般只需要三个参数。code、msg和data。
由于data的数据类型是未知且多变的,故需要传入一个范型,指定data的类型。
@Data
public class JsonResult<T> {
private T data;
private String code;
private String msg;
/**
* 若没有数据返回,默认状态码为0,提示信息为:操作成功!
*/
public JsonResult() {
this.code = "0";
this.msg = "操作成功!";
}
/**
* 若没有数据返回,可以人为指定状态码和提示信息
* @param code
* @param msg
*/
public JsonResult(String code, String msg) {
this.code = code;
this.msg = msg;
}
/**
* 有数据返回时,状态码为0,默认提示信息为:操作成功!
* @param data
*/
public JsonResult(T data) {
this.data = data;
this.code = "0";
this.msg = "操作成功!";
}
/**
* 有数据返回,状态码为0,人为指定提示信息
* @param data
* @param msg
*/
public JsonResult(T data, String msg) {
this.data = data;
this.code = "0";
this.msg = msg;
}
}
测试多种类型的返回,通过网页查看效果。
@RestController
@RequestMapping("/json")
public class JsonController {
@GetMapping("/user")
public JsonResult<User> getUser(){
User user = new User(1L,"qfnv","123456");
return new JsonResult<User>(user);
}
@GetMapping("/list")
public JsonResult<List> getUserList(){
List<User> userList = new ArrayList<>();
userList.add(new User(1L,"qfnv","654123"));
userList.add(new User(2L,"adazx","654321"));
return new JsonResult<List>(userList,"获取用户列表成功");
}
@GetMapping("/map")
public JsonResult<Map> getMap(){
Map<String,Object> map = new HashMap<>(3);
User user = new User(1L,"qfnv","123456");
map.put("作者信息" , user);
map.put("电子邮箱","[email protected]");
map.put("粉丝数","3215");
return new JsonResult<Map>(map);
}
}
{"data":{"id":1,"name":"qfnv","password":"123456"},"code":"0","msg":"操作成功!"}
{"data":[{"id":1,"name":"qfnv","password":"654123"},{"id":2,"name":"adazx","password":"654321"}],"code":"0","msg":"获取用户列表成功"}
{"data":{"粉丝数":"3215","作者信息":{"id":1,"name":"qfnv","password":"123456"},"电子邮箱":"[email protected]"},"code":"0","msg":"操作成功!"}