Jay
Jay

Reputation: 5074

Java REST API: Returning Multiple objects from API Method

I am trying to return multiple objects (such as String, Boolean, MyOwnClass, etc) from a Java REST API Method using JAX-RS in Eclipse.

Here's what I have right now:

My API Method

@Path("/")
public class myAPI {

    @GET
    @Produces({ "application/xml", "application/json" })
    @Path("/getusers")
    public Response GetAllUsers() {

        //Data Type #1 I need to send back to the clients
        RestBean result = GetAllUsers();

        //Data Type #2 I need to send with in the response
        Boolean isRegistered = true;

        //The following code line doesn't work. Probably wrong way of doing it
        return Response.ok().entity(result, isRegistered).build();
    }
}

RestBean class:

public class RestBean {
    String status = "";
    String description = "";
    User user = new User();

   //Get Set Methods
}

So I'm basically sending two data types: RestBean and Boolean.

What's the right way of sending back a JSON response with multiple data objects?

Upvotes: 2

Views: 9924

Answers (1)

sisyphus
sisyphus

Reputation: 6392

Firstly, Java conventions are that class names begin with an uppercase letter and method names with a lowercase letter. It's generally a good idea to follow them.

You need to wrap your response inside a single class, as @Tibrogargan suggests.

public class ComplexResult {
    RestBean bean;
    Boolean isRegistered;

    public ComplexResult(RestBean bean, Boolean isRegistered) {
        this.bean = bean;
        this.isRegistered = isRegistered;
    }
}

and then your resource looks like...

public Response getAllUsers() {
    RestBean restBean = GetAllUsers();
    Boolean isRegistered = true;
    final ComplexResult result = new ComplexResult(bean, isRegistered);

    return Response.ok().entity(Entity.json(result)).build();
}

What you really need to know, however, is what your response document should look like. You can only have a single response document - which is what the wrapper is for - and the way your wrapper is serialised affects how the parts of the document are accessed.

Note - you have your resource listed as being able to produce both XML and JSON and what I've done only works for json. You can get the framework to do all the content-negotiation heavy lifting for you, and that would probably be a good idea, by just returning the document type from the method rather than Response ...

public ComplexResponse getAllUsers() {
    ...
    return new ComplexResult(bean, isRegistered);

Upvotes: 6

Related Questions