json 在Java Webclient中,如何在Mono序列化中当value为null时完全省略字段

tktrz96b  于 4个月前  发布在  Java
关注(0)|答案(1)|浏览(70)

我在Java Sping Boot 框架上,试图使用Mono为WebClient序列化Java对象以用于发送。我想知道当值被发现时是否可以完全删除字段null。我似乎没有找到这样做的方法。试图找到一个注解来看看这是否有效。
下面是一个例子。
我有一个Java类,它的对象看起来像这样

public class RequestBody {
  private String name_first;
  private String name_last;
  private String email_address;
}

字符串
使用builder模式来构建它。

RequestBody requestBody =
    RequestBody.builder()
        .name_first(input.getName().getFirst())
        .name_last(input.getName().getLast())
        .build();


使用WebClient + Mono向另一个API进行RESTful POST

return requestBodySpec
      .header("Content-Type", "application/json")
      .body(Mono.just(requestBody), RequestBodyClass)
      .retrieve()
      .bodyToMono(String.class)
      .block();


Mono序列化后的JSON结果如下所示。

{
    "name_first": "Foo",
    "name_last": "Bar,
    "email_address": null
}


期望请求JSON看起来像这样。当值为null时,email_address被完全删除。我们如何做到这一点?

{
    "name_first": "Foo",
    "name_last": "Bar
}

0ve6wy6x

0ve6wy6x1#

感谢AI,答案是:创建一个Weblux配置类:

@Configuration
@EnableWebFlux

public class WebFluxConfig implements WebFluxConfigurer {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper;
    }

    @Bean
    public Encoder<Object> encoder(ObjectMapper objectMapper) {
        return new Jackson2JsonEncoder(objectMapper, MediaType.APPLICATION_JSON);
    }
}

字符串

相关问题