繁体   English   中英

Object 渲染到 Json - Spring 引导

[英]Object rendering to Json - Spring Boot

我目前正在研究 SDK 以与 API(作为客户端)集成。 我的问题是(我什至不确定这是一个问题),但我希望我的请求只包含已初始化的参数。 现在如何生成它们的示例:

{
   "scenarioKey":"",
   "bulkId":"",
   "destinations":[
      {
         "messageId":"xxxxx",
         "to":{
            "phoneNumber":""
         }
      }
   ],
   "sms":null
}

SMS 参数从未启动,因此我希望它不包含在请求正文中,这是我可以在没有此参数“ sms ”的情况下发出请求的一种方式吗?

顺便说一句,我正在使用 HttpEntity:

HttpEntity<Object> entity = new HttpEntity<>(bodyObject, headers);

If you are using jackson to serialize your JSON, you should take a look at the setSerializationInclusion() method on ObjectMapper https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper .html#setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include)

这是一个简单的测试用例,可以防止sms字段包含在 JSON output 中:

@Test
public void testJson() throws Exception {
    Addr addr = new Addr();
    addr.phoneNumber = "";
    Destination destination = new Destination();
    destination.messageId = "";
    destination.to = addr;
    Scenario scenario = new Scenario();
    scenario.scenarioKey = "";
    scenario.bulkId = "";
    scenario.destinations = Arrays.asList(destination);

    ObjectMapper mapper = new ObjectMapper()
            .enable(SerializationConfig.Feature.INDENT_OUTPUT)
            .setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

    System.out.println(mapper.writeValueAsString(scenario));
}

public static class Scenario {
    public String scenarioKey;
    public String bulkId;
    public List<Destination> destinations;
    public String sms;
}
public static class Destination {
    public String messageId;
    public Addr to;
}
public static class Addr {
    public String phoneNumber;
}

Spring 引导允许对它在 application.properties 文件中使用的 Jackson ObjectMapper 进行简单配置。

支持的属性在文档中进行了描述。 https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-customize-the-jackson-objectmapper

特别是 application.properties 中spring.jackson.default-property-inclusion=non_null应该可以解决问题。

如果您想为特定的类或属性执行此操作 Jackson 具有注释@JsonInclude(Include.NON_NULL)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM