如何创建适当的JAXB映射以使Jersey反序列化过程发生 [英] How to create proper JAXB mapping to make Jersey deserialization process happened
问题描述
我有来自WS的JSON响应:
I have JSON response from WS:
[
{
"name": "Bobby",
"status": "single"
},
{
"name": "John",
"status": "married"
}
]
这是我的包装纸
@XmlRootElement(name = "users")
public class UserListWrapper {
private List<User> users;
@XmlElement(name = "user")
public List<User> getUsers() {
return users;
}
// getters and setters omitted
}
和用户类别
@XmlRootElement
class User {
private String name;
private String status;
// getters and setters omitted
}
问题是当Jersey尝试反序列化对我的包装器对象的响应时.它说
The problem is when Jersey try to deserialize response to my wrapper object. It say
Caused by: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of com.jersey.test.UserListWrapper out of START_ARRAY token
表明我的包装器注释出了点问题.我该如何解决?
Seams that something wrong with my wrapper annotations. How can I fix them?
UPD
我发送
{
"user": [
{
"name": "Bob",
"status": "single"
},
{
"name": "Mike",
"status": "married"
}
]
}
一切正常.但是我需要这种格式
all works fine. But I need this format
[
{
"name": "Bobby",
"status": "single"
},
...
]
UPD
Jersey客户代码
Jersey Client code
HttpAuthenticationFeature authenticationFeature = HttpAuthenticationFeature.basic("user", "secret");
Client client = ClientBuilder
.newClient()
.register(authenticationFeature)
.register(JacksonFeature.class);
WebTarget target = client.target("http://localhost:8080/server/");
UserListWrapper entity;
Response resp;
resp = target.queryParam("u", "info")
.path("/rest/users")
.request()
.accept(APPLICATION_JSON)
.get();
entity = resp.readEntity(UserListWrapper.class);
推荐答案
然后忘记UserListWrapper
包装器. List<User>
非常适合JSON数组([]
)格式.如果添加包装器类,则是的,您将需要额外的JSON对象层({}
).这个:
Forget the UserListWrapper
wrapper then. List<User>
is perfect for the JSON array ( []
) format. If you add the wrapper class, then yes you will need the extra JSON object layer ( {}
). This:
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createBook(List<User> users) {
受到很好的支持(至少使用杰克逊-您正在使用).
is supported just fine (at least with Jackson - which you are using).
更新
如果来自服务器的响应以JSON数组的形式出现,那么您仍然可以将其反序列化为List<User>
.例如
If the response from the server is coming as a JSON array, then you can still deserialize it as a List<User>
. For example
WebResource resource = client.resource("...");
List<User> users = resource.get(new GenericType<List<User>>(){});
请参阅此相关文章
更新2
由于使用的是JAX-RS 2客户端API,因此可以使用重载的
Since you are using the JAX-RS 2 client API, you can use the overloaded readEntity
, which accepts a GenericType
argument also
List<User> user = response.readEntity(new GenericType<List<User>>(){});
这篇关于如何创建适当的JAXB映射以使Jersey反序列化过程发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!