users@jersey.java.net

[Jersey] Re: Jackson + StreamingOutput

From: Eric Stein <steine_at_locustec.com>
Date: Thu, 24 Apr 2014 19:32:57 +0000

Michal, thanks for the pointer! I was trying to do things the Jersey 1.x way, which explains my difficulties.



I do have a follow-up question, though. When I have a typical @GET method that returns a POJO, Jersey and Jackson do magic to ensure that the response goes out in either XML or JSON as specified by the incoming Accept header. How does that magic work, and what's the right way to replicate it for StreamingOutput?



Thanks,
Eric



-----Original Message-----
From: Michal Gajdos [mailto:michal.gajdos_at_oracle.com]
Sent: Thursday, April 24, 2014 4:37 AM
To: users_at_jersey.java.net
Subject: [Jersey] Re: Jackson + StreamingOutput



Hi Eric,



I assume you have an instance of ObjectMapper and you're passing it to

Jackson via ContextResolver mechanism. If this is not your case you can

simply create a new ObjectMapper in your StreamingOutput. However if it

is your case it's possible to inject javax.ws.rs.ext.Providers into your

resource:



@Path("helloworld")

public class HelloWorldResource {



     @Context

     private Providers providers;



     @GET

     @Produces("application/json")

     public StreamingOutput getHello() {

         final Object object = ...;



         return new StreamingOutput() {

             @Override

             public void write(final OutputStream output) throws

IOException, WebApplicationException {

                 final ContextResolver<ObjectMapper> resolver =

providers.getContextResolver(ObjectMapper.class,

                         MediaType.APPLICATION_JSON_TYPE);



                 ObjectMapper mapper = null;

                 if (resolver != null) {

                     mapper = resolver.getContext(ObjectMapper.class);

                 }

                 if (resolver == null) {

                     mapper = new ObjectMapper();

                 }



                 mapper.writeValue(output, object);

             }

         };

     }

}



Michal



On 23.04.2014, 21:30 , Eric Stein wrote:

> Sorry, I mean what is the correct way to get a JsonGenerator instance into my StreamingOutput. I have an InputStream of data, and I want to stream it out, so it is my understanding that JsonGenerator would be the way to go here?

>

> Thanks,

> Eric

>

> -----Original Message-----

> From: Eric Stein

> Sent: Wednesday, April 23, 2014 3:14 PM

> To: users_at_jersey.java.net

> Subject: Jackson + StreamingOutput

>

> I have Jackson configured to run in my Jersey 2.7 API using JacksonFeature and JacksonConfigurator. Now I have a very large text response that needs to be sent via StreamingOutput back to the client. What is the proper way to get an ObjectMapper reference into my StreamingOutput implementation?

>

> Thanks,

> Eric