- 当请求接口不返回数据时,封装后响应体传递的 JSON 数据中 data 的值就会显示为 null,整体上看起来并不协调,我们可以对 data 的空值进行处理,转化为空符串
- 我们可以自定义一个 Jackson 配置类,在配置类中使用 Jackson2ObjectMapperBuilder 来建一个 ObjectMapper 用于获取当前 ObjectMapper实例的序列化对象,然后将序列化时 null 值写入为空字符串
示例
@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; } } |
- 当业务逻辑和异常处理足够完整时,我们还可以使用 @JsonInclude(JsonInclude.Include.NON_NULL) 排除对 data 为 null 情况下的序列化显示
示例
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> { private int code; private T data; private String msg;
public Result() { }
public Result(T data) { this.code = ResultCode.SUCCESS.getCode(); this.data = data; this.msg = ResultCode.SUCCESS.getMsg(); }
public Result(ResultCode resultCode, T data) { this.code = resultCode.getCode(); this.data = data; this.msg = resultCode.getMsg(); }
public Result(ResultCode resultCode, String msg, T data) { this.code = resultCode.getCode(); this.data = data; this.msg = msg; }
public static <T> Result<T> success(T data) { return new Result<>(ResultCode.SUCCESS, data); }
public static <T> Result<T> fail(ResultCode resultCode, String msg, T data) { return new Result<>(resultCode, msg, data); }
public int getCode() { return code; }
public void setCode(int code) { this.code = code; }
public T getData() { return data; }
public void setData(T data) { this.data = data; }
public String getMsg() { return msg; }
public void setMsg(String msg) { this.msg = msg; } } |
注
空值排除建议在数据处理相对完整的情况下使用,否则在返回数据为空时会缺少 data 属性,降低数据判断的准确性