Reputation: 2199
Enviorment : Java, Jersey with Jackson, Tomcat.
I have a rest service taking JSON input from the client. I want to verify the input, if its JSON or not and then it JSON then the key in the JSON input is as expected or not. If yes then it should produce HTTP 400-Bad request.
For example-
// REST SERVICE @POST @Path("login") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response login(Credentials login, @Context HttpServletRequest httpRequest) { if (login == null) // return sendBadRequest(HTTP 400); String userName = (String) login.getUsername(); String passWord = (String) login.getPassword(); if (userName == null) // return sendBadRequest(HTTP 400); else if (passWord == null) // return sendBadRequest(HTTP 400); ..... } // Credentials.java @JsonIgnoreProperties(ignoreUnknown=true) public class Credentials { private String username; private String password; // Getters and setters... }
For example - non json input like
{"key" : "val"should produce HTTP 400. As well as input with non proper values like
{"usernames" : "abc", "passwords" : "abc"}should produce HTTP 400.
My code works well for case 2 mentioned but I expected it to work for case 1 as well. when non-json input is there, I expected it to set the Credential object to null and then I can the null object in 'if' to return HTTP 400. But it was not the case. Is there anything that rest framework provides for this case ?
Upvotes: 0
Views: 946
Reputation: 2199
After a long research I managed to find the answer for this. We have to use @Provider in rest framework to handle this error.
Here is an example for this :
@Provider public class JsonParseExceptionHandler implements ExceptionMapper { public Response toResponse(JsonParseException exception) { ResponseStatus status = new ResponseStatus(); ClientResponse clientResponse = new ClientResponse(); status.setCode(Status.BAD_REQUEST.getStatusCode()); status.setMessage(Status.BAD_REQUEST.name()); status.setFieldName("JSON Parsing Exception"); status.setFieldDescription(exception.getMessage()); clientResponse.setStatus(status); return Response .status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) .entity(clientResponse).build(); } }
Upvotes: 1
Reputation: 3794
You can use gson to convert you JSON into java object then you can validate
https://code.google.com/p/google-gson/
Or you can use Json Lib
http://json-lib.sourceforge.net/index.html
The following method will help
Upvotes: -1