I have the following resource that uses JSON to map POJOs.
@Path("example") public class ExampleResource { @POST @Consumes(MediaType.APPLICATION_JSON) public Response addThesis(MyObject myObject) { return Response.ok().entity("Test").build(); } }
Here's the POJO class:
public class MyObject { private String title; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
When I send a POST request with the body {"title": "Test title"} , everything works fine. Answer Test , as expected. However, when I change the request to {"titlee": "Test title"} , the server responds as follows:
Unrecognized field "titlee" (class com.my.package.MyObject) not marked as ignorant (one well-known property: "title"]) in [Source: org.glassfish.jersey.me ssage.internal.ReaderInterceptorExecutor$UnCloseableInputStream@ 6dc6a46a; row: 2, column: 11] (via the reference chain: com.my.package.MyObject ["titlee"])
Obviously, this is an exception, abandoned and returned by Jersey. How can I catch this exception and return a custom status code and message?
What I have tried so far is to implement my own ExceptionMapper:
@Provider public class MyJsonExceptionMapper implements ExceptionMapper<JsonProcessingException> { public Response toResponse(JsonProcessingException e) { return Response.status(400).entity("JSON Processing Error").build(); } }
Unfortunately, the answer remains the same. When I implement ExceptionMapper for a custom exception and throw the corresponding exception in the resource method, everything works fine. I assume this is due to the default ExceptionMapper for JsonProcessingException overriding my own. Then I tried to create a common mapper ("implements ExceptionMapper"), but again it fails.
I looked literally everywhere and tried a lot of things, including the ResourceConfig extension and registering my cartographer, but so far nothing has worked.
Additional information that may help reduce the problem: I use Grizzly2 as an HTTP server, which I deploy as a FAT JAR.
Part of the dependencies of my pom.xml looks like this:
<dependencies> <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-jackson</artifactId> <version>2.24</version> </dependency> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-grizzly2-http</artifactId> <version>2.24</version> </dependency> </dependencies>
Any advice is appreciated.