How to correctly enter the incoming JSON and check for the absence of properties? [Jackson, Jersey]

I am using Jackson 2.7.0. and the latest JSON for JSON on the REST API, which handles database communication with Hibernate 5+.

I do not know how to check incoming JSON if it is missing any missing properties. It is not possible to check for a primitive type if they are zero. But also I would like to use primitive types due to a performance hit. What is the best practice to solve such a problem?

When I get JSON as below, everything is fine:

{"vehicle":{"id":1},"distance":1000,"quantity":2000} 

But when I get JSON as:

{"vehicle":{"id":1},"quantity":2000}

then the distance is set to the default value 0.

My essence looks like

public class Consumption{

private int id;
private double quantity;
private double distance;

@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public Consumption(
        @JsonProperty(value = "quantity", required = true)double quantity, 
        @JsonProperty(value = "distance", required = true)double distance,
        @JsonProperty(value = "vehicle", required = false)Vehicle vehicle) {...

And the REST method:

@POST
@Path("/setConsumption/")
public Response setConsumption(@Valid Consumption consum){...

Fixed solution # 1

-1, , 0, boolean, "" .

​​ JSON?

# 2

, @JsonProperty(value = "quantity", required = true) . Jackson 2.7.0. +, . :

Missing required creator property 'distance' (index 1) at 
[Source:org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@1b72cb6; line: 1, column: 181]

, JSON . . httpCode errorMessage, . , , .

Jackson, JSON. Integer int - . JSON 60+ , .

, , .

TDLR - , (int, double, boolean,...) JSON , 60+ . Java null.

№ 1

ExceptionMapper JsonMappingException , , .

(- " ..." - ):

@Provider
public class JacksonNoPropertyMapper implements ExceptionMapper<JsonMappingException> {
    @Override
    public Response toResponse(JsonMappingException e) {

    return Response.status(999).entity("OVERRIDE TEST").type(MediaType.APPLICATION_JSON).build();
}

}

+3
1

- , , , .

public class Consumption {

private int id;
private double quantity;
private Double distance;

public boolean isDistanceSet() {
    return distance != null;
}
+1

Source: https://habr.com/ru/post/1677502/


All Articles