Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning JSONP from Jersey

Tags:

jsonp

jersey

I am currently using Jersey to return JSON. How do I return JSONP instead? For example, my current RESTful method is:

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Order> getOrders() {
    return OrderRepository.getOrders();
}

I would like to deploy on Tomcat (don't want to require the use of GlassFish). My only dependencies on Jersey are:

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.9.1</version>
    </dependency>

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>1.9.1</version>
    </dependency>

What additional dependencies are needed? How will the code change?

Thanks.
Naresh

like image 717
Naresh Avatar asked Nov 15 '12 06:11

Naresh


2 Answers

Take a look at the JSONP example (especially the ChangeList resource) in Jersey (you can download the whole project here).

What you basically need to do is something like this:

@GET
@Produces(MediaType.APPLICATION_JSON)
public JSONWithPadding getOrders() {
    return new JSONWithPadding(new GenericEntity<List<Order>>(OrderRepository.getOrders()){});
}
like image 199
Michal Gajdos Avatar answered Oct 21 '22 05:10

Michal Gajdos


It's important to modify the correct answer, as @s_t_e_v_e says. It should be something like this:

@GET
@Produces({"application/javascript"})
public JSONWithPadding getOrdersJSonP(@QueryParam("callback") String callback) {
    List<Order> orderList = OrderRepository.getOrders();
    return new JSONWithPadding(new GenericEntity<List<Order>>(orderList){}, 
                callback);
    }
like image 37
Ignacio Rubio Avatar answered Oct 21 '22 06:10

Ignacio Rubio