简体   繁体   中英

jackson json parser accepting empty single quotes for int primitives

I have defined a REST element in our project which contains attributes with primitive int & long . I am using Jersey 2.17 During testing when I tried to pass a "" string, the REST client did not report any validation errors, but in the rest resource, I get the value of the primitive as the default value 0. This behavior is very odd as an empty string should not be accepted in this case. How do I make the request fail with validation errors.

My JSON request:
JSONObject employee = new JSONObject("{name : James}");     
rateLimiter.put("age", "");

Response :
POST -><http://134.141.206.113:8080/Employee     >
data: {"name":"James","age":""}
Status :201 output: {  
  "name" : "James",
  "age" : 0
}

One way to check the payload's field for emptiness or null is by using the Jackson's annotations to skip these fields while deserializing. In this way, if a compulsory field is not present in the deserialized object then you can assume that the field was empty while the request was made.

Jackson's Annotations

  1. @JsonInclude(Include.NON_NULL)
  2. @JsonInclude(Include.NON_DEFAULT)

Add them on top where the fields are declared in the DTO/entity class

@JsonInclude(Include.NON_DEFAULT)
private int age = 0;

@JsonInclude(Include.NON_NULL)
private String name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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