I have some problem using Jersey REST webservices.
I have the following domain class:
@XmlRootElement
public class User {
private long id;
private String email;
private String forename;
private String role;
public User() {
// required for JAXB
}
// + Getters + Setters
}
and the following resource class:
@Produces(MediaType.APPLICATION_JSON)
@Path("/users")
public class UserService {
@GET
public User[] getUsers() {
User[] users = ... // Users from DB
return users;
}
}
If I request that resource (/users) I get the following json response:
{
"user":
[
{
"id":"1",
"email":"Toby@email.com",
"forename":"Toby",
"role":"admin"
}
,
{
"id":"2",
"email":"Rob@email.com",
"forename":"Rob",
"role":"developer"
}
]
}
On the client side (where I have the same User.class) I want to unmarshall this JSON response back to the corresponding POJOs. That means in this example I would like to get two Object of type User. I did some experimental stuff with GSON like
User[] users = gson.fromJson(JSONString, User[].class)
but was not able to get it working. Exception:
JSONParseException: Expecting object but found array
Can anyone tell me what Iam doing wrong here? Or is my json format the problem?
Edit: Tried it with an own implementation of a collection type adapter as mentioned here:
Type usersType = new TypeToken<List<User>>() {}.getType();
List<User> users = new ArrayList<User>();
users = gson.fromJson(reader, usersType);
Now Iam getting an JsonParseException:
The JsonDeserializer failed to deserialize Json Object {"user":[{"id":"1","email":"Toby@email.com","forename":"Toby",....