360产品展示网站,WordPress的app模板,网页导航栏图片,做网站排名大概要多少一、针对特定接口null的处理#xff1a;
方法一#xff1a;使用 JsonInclude 注解
1.1 类级别#xff1a;在接口返回的 DTO 类或字段 上添加 JsonInclude 注解#xff0c;强制忽略 null 值#xff1a;
类级别#xff1a;所有字段为 null 时不返回
JsonInclude(Js…一、针对特定接口null的处理
方法一使用 JsonInclude 注解
1.1 类级别在接口返回的 DTO 类或字段 上添加 JsonInclude 注解强制忽略 null 值
类级别所有字段为 null 时不返回
JsonInclude(JsonInclude.Include.NON_NULL)
public class MyResponseDTO {private String field1;
1.2 字段级别在具体字段上仅该字段为 null 时不返回
// 字段级别仅该字段为 null 时不返回
JsonInclude(JsonInclude.Include.NON_NULL)
private String field2;1.3 方法级别 在方法级别使用 JsonInclude
如果不想在 DTO 类上全局标注 JsonInclude可以直接在 Controller 方法的返回类型上通过 JsonSerialize 注解临时指定序列化行为。
GetMapping(/user)
JsonSerialize(include JsonSerialize.Inclusion.NON_NULL) // 旧版 Jackson 注解
public MyResponse getUser() {MyResponse response new MyResponse();response.setName(Alice); // age 为 null不返回return response;
}方法二动态构建响应对象
在 Controller 方法中手动过滤 null 值使用 Map 或 JSONObject 动态构建响应体
GetMapping(/api)
public MapString, Object getData() {MyResponseDTO dto service.getData();MapString, Object result new HashMap();if (dto.getField1() ! null) {result.put(field1, dto.getField1());}return result;
}适用于简单场景但需手动维护字段映射。
方法三自定义序列化逻辑针对复杂场景
通过继承 JsonSerializer 实现特定字段的 null 处理逻辑并在 DTO 中指定序列化器
public class NullSerializer extends JsonSerializerObject {Overridepublic void serialize(Object value, JsonGenerator gen, SerializerProvider provider) {// 忽略 null 字段if (value null) {return;}gen.writeObject(value);}
}// 在 DTO 字段上指定序列化器
public class MyResponseDTO {JsonSerialize(using NullSerializer.class)private String field1;
}适用于需要精细化控制序列化逻辑的场景。
方法四自定义 ObjectMapper 并局部使用
通过注入 ObjectMapper 实例在特定接口中手动序列化数据跳过 null 值。
Autowired
private ObjectMapper objectMapper;GetMapping(/user)
public String getUser(HttpServletResponse response) throws JsonProcessingException {MyResponse data new MyResponse();data.setName(Alice); // age 为 null// 临时配置 ObjectMapper 忽略 nullobjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);String json objectMapper.writeValueAsString(data);// 恢复全局配置可选objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);response.setContentType(MediaType.APPLICATION_JSON_VALUE);return json;
}注意此方法需手动处理响应适用于需要完全控制序列化逻辑的场景但需谨慎管理 ObjectMapper 的线程安全性。
方法五使用 ResponseBodyAdvice 全局拦截并处理
通过实现 ResponseBodyAdvice 接口对特定接口或全局返回值进行统一处理。 定义切面类 RestControllerAdvice
public class NullIgnoreAdvice implements ResponseBodyAdviceObject {Overridepublic boolean supports(MethodParameter returnType, Class converterType) {// 仅处理特定接口根据注解、包路径等条件判断return returnType.getExecutable().getName().equals(getUser);}Overridepublic Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType mediaType, Class selectedConverterType,ServerHttpRequest request, ServerHttpResponse response) {if (body instanceof MyResponse) {// 手动移除 null 值需根据数据结构处理((MyResponse) body).setAge(null); // 示例}return body;}
}结合 ObjectMapper 动态过滤 在 beforeBodyWrite 中重新序列化数据 ObjectMapper mapper new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.convertValue(body, returnType.getParameterType());二、针对所有接口null 的处理
2.1 全局配置影响所有接口
若需所有接口忽略null值可在application.properties中配置
spring.jackson.default-property-inclusionnon_null2.2 Springboot 整合 fastjson:
在springboot 启动类中定义该方法即可 Beanpublic HttpMessageConverters fastJsonHttpMessageConverters() {FastJsonHttpMessageConverter4 fastConverter new FastJsonHttpMessageConverter4();FastJsonConfig fastJsonConfig new FastJsonConfig();fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.IgnoreNonFieldGetter,SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty);fastConverter.setFastJsonConfig(fastJsonConfig);List supportedMediaTypes new ArrayList();supportedMediaTypes.add(new MediaType(text, json, Charset.forName(utf8)));supportedMediaTypes.add(new MediaType(application, json, Charset.forName(utf8)));fastConverter.setSupportedMediaTypes(supportedMediaTypes);HttpMessageConverter? converter fastConverter;return new HttpMessageConverters(converter);}2.3 Springboot 整合 jackson:
Configuration
public class JacksonConfig {BeanPrimaryConditionalOnMissingBean(ObjectMapper.class)public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {ObjectMapper objectMapper builder.createXmlMapper(false).build();objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializerObject() {Overridepublic void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {jsonGenerator.writeString();}});return objectMapper;}
}三、总结
针对新项目推荐使用全局序列化处理统一返回值。针对老项目推荐使用特定接口的处理避免影响了其他接口的稳定。