Quarkus REST client avoid JSON serialization of Null Fields
I need to send on a remote service an update request in order to update some fields. The remote service use a application/json
content type, so I have implemented my rest client like:
@RegisterRestClient @Path("/api/v1") @Produces("application/json") @Consumes("application/json") @ApplicationScoped public interface ServiceClient { @POST @Path("/path_to_update/{uuid}") Response updateAttributes( @PathParam("uuid") String uuid, Attributes attributes ); } @NoArgsConstructor @Data @AllArgsConstructor @Builder public class Attributes { private AttributesA a; private AttributesB b; } @NoArgsConstructor @Data @AllArgsConstructor @Builder public class AttributesA { private String field1; } @NoArgsConstructor @Data @AllArgsConstructor @Builder public class AttributesB { private String field2; private String field3; }
I need to update only a subset of the fields. maybe field1
and field3
. So in this case the field2
will be set to null
.
The remote service dosen’t accept a null
as a parameter value so I need to avoid to serialize all the field that have null
value.
My project use jsonb
and I have already try to annotate the model classes with JsonbNillable
without any success.
Is there a vay to configure the rest client in order to avoid the serialization of null fields?
I would suggest dropping Lombok for your data classes to give more clarity when things are not working as expected like this. In this case, you can actually write the code more concisely without lombok by using JSON-B’s default visibility strategy, which means public fields are [de]serailized automatically and don’t need to have getter/setters.
So your data classes could be:
public class Attributes { public AttributesA a; public AttributesB b; } public class AttributesA { public String field1; } public class AttributesB { public String field2; public String field3; }
Is there a way to configure the rest client in order to avoid the serialization of null fields?
By default JSON-B does not serialize null values. So if we did:
Attributes empty = new Attributes(); String json = jsonb.toJson(empty); System.out.println(json); // "{}"
We would just get an empty JSON object of {}
. The @JsonbNillable
annotation is useful if you do want to serialize null values as null
.