Rickesh John Rickesh John -4 years ago 191
Java Question

How to handle parser exceptions during unmarshalling of JSON data?

I am using Jersey in my Web-application. The data sent to the server is in JSON format, which in turn is unmarshalled at the server-end and the object obtained is used in further processing. The security audit raised some vulnerabilities for this approach.

My Rest Code:

public Response registerManga(MangaBean mBean){
return Response.status(200).build();


public class MangaBean {
public String title;
public String author;

public String toString() {
return "MangaBean [title=" + title + ", author=" + author + "]";
public String getTitle() {
return title;
public void setTitle(String title) {
this.title = title;
public String getAuthor() {
return author;
public void setAuthor(String author) {
this.author = author;


The data is sent in this format:

["title":"Bleach","author":"kubo tite"]

The above data is successfully unmarshalled into an object and I get this as the output:

MangaBean [title=Bleach, author=kubo tite]

But if the data is changed to:

["title":"<script>alert("123");</script>","author":"kubo tite"]

A 500 internal server error occurs and is displayed to the user:

javax.servlet.ServletException: org.codehaus.jackson.JsonParseException: Unexpected character ('1' (code 49)): was expecting comma to separate OBJECT entries
at [Source: org.apache.catalina.connector.CoyoteInputStream@19bd1ca; line: 1, column: 28]

The unexpected occurrence of
is causing errors in the parser. As the unmarshalling is done behind the scenes and I have no control over it, I am unable to handle the exception being raised.

My question is how can I handle this exception and return a proper response to the user instead of a stacktrace. Please advice.

Answer Source

Register an exception mapper to handle the JSON parsing exceptions:

class JSONParseExceptionMapper implements ExceptionMapper< JsonParseException > {
    public Response toResponse(final JsonParseException jpe) {
        // Create and return an appropriate response here
        return Response.status(Status.BAD_REQUEST)
                .entity("Invalid data supplied for request").build();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download