Spring Boot教程之四十五:使用 Jackson 在 Spring Boot 的 REST API 实现中使用 JSON

 使用 Jackson 在 Spring Boot 的 REST API 实现中使用 JSON

每当我们使用Spring(Spring Boot)实现REST API时,我们都会遇到在API 的JSON响应中排除 NULL 的需求。此外,可能还需要外部化打开/关闭此功能:在 JSON 响应中排除 NULL,从而允许 API 的使用者根据需要进行自定义。

在本文中,我们总结了使用 Jackson 实现上述功能的 ON/OFF 外部化的方法- Jackson 是一个基于 Java 的库,用于将 Java 对象序列化或映射到 JSON,反之亦然。

不成功的方法:

最初,我们尝试了 Spring Boot 现有的方法,但没有成功,例如:

  • 在application.properties中具有spring.jackson.default-property-inclusion属性。此属性采用以下值:always / non_null / non_absent / non_default / non_empty
  • 扩展WebMvcConfigurationSupport类并定制 Spring Boot 配置,见下文。
  • Java

@Configuration

class WebMvcConfiguration extends WebMvcConfiguration{

    @Override

    protected void extendsMessageConverters

      (List<HttpMessageConverter<?>> converters)

    {

        for(HttpMessageConverter<?> converter: converters)

        {

            if(converter instnceof MappingJackson2HttpMessageConverter)

            {

                ObjectMapper mapper = 

                  ((MappingJackson2HttpMessageConverter)converter)

                  .getObjectMapper();

                mapper.setSerializationInclusion(Include.NON_NULL);

                }

            }

        }

现在,创建org.springframework.http.converter.json.Jackson2ObjectMapperBuilderCustomizer的实例,下面给出的代码供您参考。

  • Java

@Bean

Public Jackson2ObjectMapperBuilderCustomizer customJackson(){

    return new Jackson2ObjectMapperBuilderCustomizer(){

    @Override

    public void customize(Jackson2ObjectMapperBuilder builder){

        builder.serializationInclusion(Include.NON_NULL);

        builder.failonUnknownProperties(false);

        }

    };

}

成功的方法:

如果尚未创建,则创建一个 JSON 响应对象。这是在序列化为 JSON 时您想要基于application.properties中的属性“排除/包含空字段”功能的对象。您可以在下方查看响应对象以供参考。

  • Java

public class RegistrationResponse{

  

    @JsonProperty("success")

    private Boolean success = null;

      

    @JsonProperty("message")

    private String message = null;

      

    @JsonProperty("data")

    private String data = null;

      

    @JsonProperty("error_code")

    private Integer errorCode = null;

      

    public RegistrationResponse success(Boolean success){

        this.success = success;

        return this;

        }

          

        @NotNull

        public Boolean isSuccess(){

            return success;

            }

        public void setSuccess(Boolean success){

            this.success = success;

        }

          

        public RegistrationResponse message(String message){

            this.message = message;

            return this;

            }

              

        @NotNull

        public String getMessage(){

            return message;

        }

          

        public void setMessage(String message){

            this.message = message;

        }

创建一个名为“ config.response.json.format.exclude_null ”的属性,其值可以是“ true ”或“ false ”。值“ true ”表示排除 JSON 响应中的空字段,值“ false ”表示不排除空字段。此外,将此属性绑定到类级属性,以便可以读取该值,下面给出的代码供您参考。

config.response.json.format.exclude_null = false

@Value(“${config.response.json.format.exclude_null}”)

私有布尔值toExcludeNull;

通过创建com.fasterxml.jackson.databind.ObjectMapper的实例来实现根据全局属性值排除空值的实际逻辑。

  • 如果全局属性值为 true ,则将创建的映射器的SerializationInclusion属性设置为Include.NON_NULL ,否则设置为Include.ALWAYS
  • 使用映射器将 Response 对象序列化为字符串并返回该字符串。确保处理 JsonProcessingException

让我们下面看看在构建 JSON 响应作为 API 实现的一部分时要添加的实际代码片段。

  • Java

RegistrationResponse regResp = new RegistrationResponse();

  

regResp.setSuccess(true);

regResp.setErrorCode(null);

 regResp.setData("testdata");

regResp.setMessage("success");

  

ObjectMapper mapper = new ObjectMapper()

mapper.enable(SerializationFeature.INDENT_OUTPUT);

  

if(toExcludeNull) mapper.setSerializationInclusion(Include.NON_NULL);

else mapper.serializationInclusion(Include.ALWAYS);

  

String regRespStr = null;

try{

  

    regRespStr = mapper.writeValueAsString(regResp);

    }

    catch(JsonProcessingException e)

        e.printStackTrace();

        }

    System.out.println("Formatted JSON Response:" + regRespStr);

这里,regRespStr是应用了 NULL 排除/包含的 JSON 字符串。  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潜洋

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值