spring boot 读书笔记2-返回Json数据及数据封装
创建实体类
public class User {
private Integer id;
private String username;
private Integer age;
public void setId(Integer id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getId() {
return id;
}
public String getUsername() {
return username;
}
public Integer getAge() {
return age;
}
public User(Integer id,String username,Integer age){
this.id=id;
this.username=username;
this.age=age;
}
创建controller
package com.example.spring2.controller;
import com.example.spring2.entity.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api")
public class UserController {
@RequestMapping("getUser")
public User getUser(){
return new User(1,"测试",10);
}
@RequestMapping("getList")
public List<User> getList(){
List<User> myuser=new ArrayList<>();
myuser.add(new User(2,"网名",55));
myuser.add(new User(3,"订单名",15));
myuser.add(new User(4,"嗯嗯名",25));
return myuser;
}
@RequestMapping("/map")
public Map<String, Object> getMap() {
Map<String, Object> map = new HashMap<>(3);
User user = new User(1, "事实上", 34);
map.put("作者信息", user);
map.put("博客地址", "http://www.baidu.com");
map.put("CSDN地址", null);
map.put("粉丝数量", 4153);
return map;
}
}
需要对null值处理时
jackson
package com.example.spring2.config;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
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 java.io.IOException;
@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, IOException {
jsonGenerator.writeString("");
}
});
return objectMapper;
}
}
fastjson
package com.example.spring2.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/*@Configuration
public class fastJsonConfig extends WebMvcConfigurationSupport {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(
// 保留map空的字段
SerializerFeature.WriteMapNullValue,
// 将String类型的null转成""
SerializerFeature.WriteNullStringAsEmpty,
// 将Number类型的null转成0
SerializerFeature.WriteNullNumberAsZero,
// 将List类型的null转成[]
SerializerFeature.WriteNullListAsEmpty,
// 将Boolean类型的null转成false
SerializerFeature.WriteNullBooleanAsFalse,
// 避免循环引用
SerializerFeature.DisableCircularReferenceDetect);
converter.setFastJsonConfig(config);
converter.setDefaultCharset(StandardCharsets.UTF_8);
List<MediaType> mediaTypeList = new ArrayList<>();
// 解决中文乱码问题,相当于在Controller上的@RequestMapping中加了个属性produces = "application/json"
mediaTypeList.add(MediaType.APPLICATION_JSON);
converter.setSupportedMediaTypes(mediaTypeList);
converters.add(converter);
}
}*/
封装统一返回的数据结构
创建实体类
package com.example.spring2.entity;
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;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
创建返回封装格式的controller
package com.example.spring2.controller;
import com.example.spring2.entity.JsonResult;
import com.example.spring2.entity.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/newapi")
public class JsonResultController {
@RequestMapping("getUser")
public JsonResult<User> getUser(){
return new JsonResult<>( new User(1,"测试",10));
}
@RequestMapping("getList")
public JsonResult<List<User>> getList(){
List<User> myuser=new ArrayList<>();
myuser.add(new User(2,"网名",55));
myuser.add(new User(3,"订单名",15));
myuser.add(new User(4,"嗯嗯名",25));
return new JsonResult<> (myuser,"获取成功");
}
@RequestMapping("/map")
public JsonResult<Map<String, Object>> getMap() {
Map<String, Object> map = new HashMap<>(3);
User user = new User(1, "事实上", 34);
map.put("作者信息", user);
map.put("博客地址", "http://www.baidu.com");
map.put("CSDN地址", null);
map.put("粉丝数量", 4153);
return new JsonResult<> (map);
}
}

浙公网安备 33010602011771号