1

In short: I'd like to return different JSONs, with say less attributes, when a request comes from a phone than when it comes from a desktop pc.


I want to build a REST service. The service will serve data based on JPA entities. The service is declared with @Path.

Depending on the User-Agent header, I want to serve a richer JSON for desktop than for mobile devices. Selection to be done serverside.

Is there a better way than to build a second serializer and use a condition (if(request useragent ) to call them (in every method) and be forced to return some String instead of any Object (making @Produces annotation unused).

Thank you

Jerome_B
  • 1,079
  • 8
  • 15
  • @Keerthivasan : the goal would be to have something, that does it by configuration so that the code keeps simple. I thought of different serializers based on the content-type (that I would change according to the user agent at the reverse proxy level), using @ Consumes. The ideal, would be one method with one @ Path annotation. – Jerome_B Sep 08 '14 at 11:07

2 Answers2

0

One way it to add a PathParam or QueryParam to the Path to tell the device type in the request, so the service can be able to understand the type of device, from which the request is and create the appropriate JSON.

Please check the most voted SO answer to find out whether the request is from mobile or desktop and add the parameter accordingly

Community
  • 1
  • 1
Keerthivasan
  • 12,760
  • 2
  • 32
  • 53
0

You can use jax-rs resource selector, which will use different sub-resource depending on user-agent string.

@Path("api")
public UserResource getResourceByUserAgent() {
    //the if statement will be more sophisticated obviously :-)
    if(userAgent.contains("GT-I9505") {
        return new HighEndUserResource();
    } else {
        return new LowEndUserResource();
    }
}

interface UserResource {User doSomeProcessing()}

class HighEndUserResource implements UserResource {

    @Path("process")
    public User doSomeProcessing() {
        //serve 
    }        

}

class LowEndUserResource implements UserResource {

    @Path("process")
    public User doSomeProcessing() {
        //serve content for low end
    }        
}

By invoking "/api/process" resource the response will depend on userAgent. You can also easily extend the solution for other devices, and implement MiddleEndUserResource for example.

You can read more information about sub-resources here:

Tomas Bartalos
  • 1,256
  • 12
  • 29