RestEasy: Could not find MessageBodyWriter for response object of type: java.util.ArrayList of media type: application/json

萝らか妹 提交于 2021-02-07 11:51:43

问题


message: Could not find MessageBodyWriter for response object of type: java.util.ArrayList of media type: application/json

Description: The server encountered an internal error (Could not find MessageBodyWriter for response object of type: java.util.ArrayList of media type: application/json) that prevented it from fulfilling this request

@GET
@Path("/{userName}/questions")
//@Produces("application/json")
public Response getUserQuestions(@PathParam("userName") String userName){               
    UserDAO userDAO = new UserDAO();        
    List<Question> questions = userDAO.getUserQuestionsByUserName(userName);        
    GenericEntity<List<Question>> entity = new GenericEntity<List<Question>>(questions){};      
    return Response.status(200).entity(entity).type(MediaType.APPLICATION_JSON).build();
}

I have got the resteasy jackson provider in the classpath. Tried changing the return type form ArrayList to List, then wrapping it in GenericEntity based on resteasy response, but still getting the same issue.

Running on tomcat7.

Thanks.


回答1:


I solved this exception by adding resteasy-jackson-provider.jar to classpath Refer https://bitbucket.org/arcbees/gaestudio/issue/2/need-resteasy-jackson-provider-on




回答2:


finally solved it using the Gson library instead of relying on json. did not wrap in Generic Entity either. Here is the code that works

@GET
@Path("/{userName}/questions")
public Response getUserQuestions(@PathParam("userName") String userName){               
    UserDAO userDAO = new UserDAO();        
    List<Question> questions = userDAO.getQuestionsByUserName(userName);        
    Gson gson = new GsonBuilder().setExclusionStrategies(new UserQuestionsExclStrat()).create(); //.serializeNulls()
    String json = gson.toJson(questions);
    System.out.println(json); 
    return Response.status(200).entity(json).build();
}

Had to use the exclusion strategy to avoid cyclic reference. here is the link for that:stackoverflow error during json conversion (hibernate bi-directional mapping)




回答3:


Faced same issue resolved by adding @XMLRootElement in class used in ArrayList




回答4:


By adding this dependency I was able to solve this issue.

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


来源:https://stackoverflow.com/questions/19089781/resteasy-could-not-find-messagebodywriter-for-response-object-of-type-java-uti

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!