Reputation: 301
I am currently working on an SDK for integrating with an API (as Client). My problem is (I am not even sure this is a problem), but I wanted my request to only contain the parameters that are initialized. Example of how they are being generated now:
{
"scenarioKey":"",
"bulkId":"",
"destinations":[
{
"messageId":"xxxxx",
"to":{
"phoneNumber":""
}
}
],
"sms":null
}
The SMS parameter was never initiated hence I wanted it not to be included in the request body, is that a way I can have a request without this parameter "sms"?
By the way I am using HttpEntity:
HttpEntity<Object> entity = new HttpEntity<>(bodyObject, headers);
Upvotes: 0
Views: 482
Reputation: 1914
Spring boot allows simple configuration of the Jackson ObjectMapper it uses in the application.properties file.
The supported properties are described in the documentation. (https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-customize-the-jackson-objectmapper)
Specifically spring.jackson.default-property-inclusion=non_null
in the application.properties should do the trick.
If you want to do this for specific classes or attributes Jackson has the annotation @JsonInclude(Include.NON_NULL)
.
Upvotes: 1
Reputation: 648
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)
Here is a simple testcase that prevents the sms
field from being included in the 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;
}
Upvotes: 1