Aditya Aditya - 4 months ago 15
JSON Question

Json response severe error in jersey REST application

I'm learning JERSEY REST API with maven. I'm getting following error whey i hit GET request. Interesting point is when i return only specific class object, i'm getting the desired result but when i return a map of all those objects i'm getting this error with Status 500 - Internal Server Error. Please suggest.

Error:

SEVERE: MessageBodyWriter not found for media type=application/json,
type=class java.util.HashMap, genericType=java.util.Map<java.lang.Integer, message.Message>.


Error prone:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Map<Integer,Message> getAll(){
ms.sample();
return ms.getAllMessages();

}


Same code but returning specific object, works fine:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Message getAll(){
ms.sample();
return ms.getAllMessages().get(1);

}


P.S : I've added json related element in pom.xml file as follows

<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>


I'm using Maven v2.16

Answer

MOXy and Maps are not friends... I recommend you using Jackson instead of MOXy to (de)serialize JSON.

To do it, remove the jersey-media-moxy dependency and add the following:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.23.1</version>
</dependency>

For more details, check Jersey documentation.

Comments