3

Here is my example: Java:

 @JsonProperty("id")
private String id;
@JsonProperty(value = "name", required = true)
private String deviceName;

I made the name as a required field. In request how to make it as required field. I should send the name value from request.

But when I enter this:

{ "id": "abc123",}

It should send error response back.

Please help me.

Matt
  • 379
  • 3
  • 9
vamsi
  • 381
  • 5
  • 10

1 Answers1

2

Jacksons JsonProperty Annotation is not used for Validation. see: Jackson @JsonProperty(required=true) doesn't throw an exception. But you can use Bean Validation, e.g.:

class Device {

    @JsonProperty("id")
    private String id;

    @NotEmpty
    @JsonProperty(value = "name")
    private String deviceName;
}
Community
  • 1
  • 1
Meiko Rachimow
  • 4,664
  • 2
  • 25
  • 43
  • But its not working. I annotated deviceName as @NotNull and I am not sending deviceName from postman, it is not throwing error still it is executing with deviceName as null. – vamsi Mar 22 '16 at 20:20
  • you could try @NotEmpty – Meiko Rachimow Mar 22 '16 at 20:22
  • please have a look at this link, how to enable the validation. https://jersey.java.net/documentation/latest/bean-validation.html#d0e13383 – Meiko Rachimow Mar 22 '16 at 20:23
  • you have to place @Valid at the declared paramter in your resource method, not in the Entity-Class (exceptions are nested beans). – Meiko Rachimow Mar 22 '16 at 20:25
  • I added @Valid for bean validation. But it is also not working. @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response details(@Valid Device device) { – vamsi Mar 22 '16 at 20:28
  • looks correct! jersey-bean-validation is in your class path? – Meiko Rachimow Mar 22 '16 at 20:29
  • Isnt it part of core-jersey? – vamsi Mar 22 '16 at 20:37
  • no: org.glassfish.jersey.ext jersey-bean-validation 2.22.2 – Meiko Rachimow Mar 22 '16 at 20:38
  • I added it and still it is going through. I use gradle so dependency is 'org.glassfish.jersey.ext:jersey-bean-validation:2.22.2' – vamsi Mar 22 '16 at 20:42
  • yes: javax.validation.Validation is the right annotation. I think you have the right dependency in your class path. So all should work... please have a look at: https://jersey.java.net/documentation/latest/bean-validation.html#d0e13383 – Meiko Rachimow Mar 22 '16 at 20:46
  • if you still have a problem registering the entity-validation feature, you could ask another question and show the resource methods, entity class and Application configuration. – Meiko Rachimow Mar 22 '16 at 20:51