[英]How to unmarshall JAX-RS Webservice response (JSON Array) correctly?
I have some problem using Jersey REST webservices. 使用Jersey REST Web服务时遇到一些问题。
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: 如果我请求该资源(/用户),则会收到以下json响应:
{
"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. 在客户端(我有相同的User.class),我想将此JSON响应编组回对应的POJO。 That means in this example I would like to get two Object of type User. 这意味着在此示例中,我想获取两个类型为User的Object。 I did some experimental stuff with GSON like 我对GSON做过一些实验性的工作,例如
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? 还是我的json格式是问题?
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: 现在我得到一个JsonParseException:
The JsonDeserializer failed to deserialize Json Object {"user":[{"id":"1","email":"Toby@email.com","forename":"Toby",....
it really was the format of the json response! 确实是json响应的格式! with the help of this post I bypassed the Object->XML->JSON way to a direct Object->JSON transformation which leads to a clean JSON syntax interpretable by gson. 在这篇文章的帮助下,我绕过了Object-> XML-> JSON方式直接进行Object-> JSON转换,这导致了由gson可以解释的干净JSON语法。 will update the answer with my full example source soon. 将很快用我完整的示例源更新答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.