简体   繁体   中英

Return list as json using jersey/spring rest server giving errors?

I want to be able to add a new header to my response. I am getting the error:

org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo SEVERE: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=class java.util.ArrayList.

My code is as follows:

@GET
 @Path("/persons")
 @Produces({ MediaType.APPLICATION_JSON })
 public Response getPersons()
 {
    List<Person> persons = new ArrayList<Person>();
    persons.add(new Person(1, "John Smith"));
    persons.add(new Person(2, "Jane Smith"));

 return Response.ok(persons).build();
 }

When I use "List" as the return type and return "persons", there is a successful return, but when I return a "Response" I get the error. How do I get rid of this?

The exception tells that you don't have MessageBodyWriter provider. Basically, because of MediaType.APPLICATION_JSON it means that you need some json framwork in your dependencies or custom implementation for @Provider More info about providers 1.1 JAX-RS (can't find JSR 339 spec online, can download pdf from here 2.0 JAX-RS )

Probably this will solve it for you:

For gradle

compile 'org.glassfish.jersey.media:jersey-media-json-jackson:2.22.2'

For Maven

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

Choose appropriate version for yours setup from here http://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson

Btw: SO LINK , SO LINK , SO LINK , SO LINK


Update after @peeskillet comment.

Good point with that there is already some json assosiated provider, but it can't marshal Response with List for some reason. I can't say much about it, because we need to see your setup (pom or gradle build file) or you could try to use something like https://stackoverflow.com/a/6081716/1032167 or this https://stackoverflow.com/a/35039968/1032167 to solve it.


So, use (option 1) Jackson or use (option 2)

GenericEntity<List<Person>> entity = new GenericEntity<List<Person>>(persons) {};
Response.ok(entity).build();

Register Jackson feature into your Jersey config. This will automatically adds Jackson inbound and outbound mapping features to Jersey.

public class JerseyConfig extends ResourceConfig {
    public JerseyConfig() {
        ...
        register(JacksonFeature.class);
        ...
    }

See https://jersey.java.net/documentation/latest/media.html#json.jackson for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM