Home > database >  How do I handle optional and extra json parameters in Java Spring?
How do I handle optional and extra json parameters in Java Spring?

Time:06-28

So when providing a JSON/HTTP API built in Java Spring Boot, and trying to read a JSON object POSTed into my service, I get using @RequestBody to read this input and parse it into a usable Java object automatically.

However, I am trying to figure out how to best keep the interface non-brittle to changes over time in the interface between microservices.

  1. How can I handle cases of optional and extra (unused) parameters provided by the requestor in the request JSON payload? Maybe this is a field that I used to require and no longer do, but the requestor hasn't been updated yet. In weak types languages these tend to just be ignored. But I'm not sure how this works in Java

  2. As a requestor using WebClient, how do I handle cases where the service I'm calling returns extra fields that I don't need, but also wasn't expecting?

CodePudding user response:

If you want to ignore properties from the JSON which are unknown from the point of view of your application, you can use the annotation @JsonIgnoreProperties(ignoreUnknown = true) above the class declaration, e.g.

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyDto{}

This will work both for WebClient and the server.

CodePudding user response:

you could set json config to ignore null or even empty field ,like this:

ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

  • Related