Java Reference
In-Depth Information
LISTING 13‐2: Responding to the client with a JSON payload
package co.uk.devchronicles.forum;
import java.util.ArrayList;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@ApplicationPath("/")
@Path("users")
public class Users extends Application{
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getUsers(){
ArrayList<User> allUsers = this.findAllUsers();
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
for(User user : allUsers){
jsonArrayBuilder.add(
Json.createObjectBuilder()
.add("id", user.getId())
.add("firstname", user.getFirstname())
.add("lastname", user.getLastname())
);
}
return Response.ok(jsonArrayBuilder.build()).build();
}
public ArrayList<User> findAllUsers(){
ArrayList<User> allUsers = new ArrayList<>();
allUsers.add(new User(123456, "Alex","Theedom"));
allUsers.add(new User(456789, "Murat","Yener"));
return allUsers;
}
}
Listing 13‐2 generates a JSON object from the user data that's in the database (for
brevity, a method is used to return the user data) and sends it back to the client with a
200 HTTP response code. The i rst thing you will notice is that the getUsers() method
Search WWH ::




Custom Search