Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a List<String> from Rest call

I'm trying to return a List in a few different media types. I'm hosting this on glassfish 4.

@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
public List<String> getSessions(){
    return Arrays.asList("foo","bar");
}

If I do a plain GET without specifying the type, I get a 500 internal server error. Specifying application/json also gives me a 500 internal server error. The server log shows absolutely no errors.

If I do a GET with Accept: text/plain, I get the following:

org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=text/plain, type=class java.util.Arrays$ArrayList, genericType=java.util.List.

I would have thought glassfish could figure out what to do with basic collection classes here. They silently fail when I try to parse them into json and apparently don't have a messagebodywriter to turn them into strings. Am I missing something obvious?

Update I've added Jackson as a jaxrs json provider using the instructions here: https://github.com/FasterXML/jackson-jaxrs-providers

Apparently with the current release, I do not need to specifically register JacksonFeature.class, nor am I able to, because there is no JacksonFeature class, just a JacksonFeatures interface.

I added this dependency to my project:

<dependency>
  <groupId>com.fasterxml.jackson.jaxrs</groupId>
  <artifactId>jackson-jaxrs-json-provider</artifactId>
  <version>2.3.0</version>
</dependency>

I am now able to return json if I do so through a Response object as follows:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getSessions(){
    Response r = Response.ok(Arrays.asList("foo","bar")).build();
    return r;
}

However, attempting to return List still fails with a 500 internal server error and no message to the server error log.

I'm willing to use the Response method if this is the correct approach, but it seems like the other way should work.

like image 652
Alex Pritchard Avatar asked Apr 15 '26 05:04

Alex Pritchard


1 Answers

You have to enable JSON support for Jersey (the JAX-RS implementation in Glassfish). Here you can find the details:

  • Enable JSON
  • Use Jackson or use Moxy

By the way this minimal configuration was enough for me after adding the jersey-media-json-jackson dependency:

@ApplicationPath("/rest")
public class App extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        final Set<Class<?>> classes = new HashSet<>();
        // enable JSON support through Jackson
        classes.add(JacksonFeature.class);
        // my rest service
        classes.add(MyRESTService.class);
        return classes;
    }
}
like image 63
mihu86 Avatar answered Apr 16 '26 21:04

mihu86



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!