Reputation: 149
I'm experimenting the Restlet framework with AppEngine and I try to retrieve a list of Object (ArrayList for instance) to a JSON representation with JAX-rs Resource
For instance a sample User class:
public class User {
private String lastname;
private String firstname;
public User(){};
public User(String lname,String fname){
this.firstname = fname;
this.lastname = lname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
}
I want to retrieve a list of User like this
@GET @Path("users")
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<User> getUsers() {
ArrayList<User> users = new ArrayList<User>();
users.add(new User("userlastname1", "userfirstname1"));
users.add(new User("userlastname3", "userfirstname2"));
return users;
}
and I want to get this JSON representation
[
{
lastname: "userlastname1",
firstname: "userfirstname1"
},
{
lastname: "userlastname2",
firstname: "userfirstname2"
}
]
What is the best way to achieve this?
The Restlet documentation mentioned the serialization proccess is automated, yes it's the case for only one Object like "User"
new User("userlastname1", "userfirstname1")
return me the good JSON representation
{
lastname: "userlastname1",
firstname: "userfirstname1"
}
If some one can give me some explanation/sample code/idea about that. much appreciated
Best regards
Upvotes: 4
Views: 1926
Reputation: 10422
@Path("/users")
public interface IUserRoutes
{
@GET
Response getUsers();
}
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class UserRoutesImpl implements IUserRoutes
{
public Response getUsers()
{
return new UserResponse().getUsers();
}
}
public class UserResponse
{
public Response getUser()
{
List<Users> users = new UserModel().getUsers();
return Response.ok(users).build();
}
}
Your User object should be a POJO.
public class User
{
private String firstName;
private String lastName;
public String getFirstname()
{
return firstName;
}
public String getLastname()
{
return lastName;
}
//etc
}
Upvotes: 1
Reputation: 1454
I actually just figured this out for myself using the Java EE edition of Restlet. Not sure if this module is available for the GAE sandbox, but I just added the Restlet extension for Jackson as a dependency and it worked like a charm.
If you are using Maven:
<dependency>
<groupId>org.restlet.jee</groupId>
<artifactId>org.restlet.ext.jackson</artifactId>
<version>2.0.10</version>
</dependency>
Upvotes: 1