问题
I have JSON response from WS:
[
{
"name": "Bobby",
"status": "single"
},
{
"name": "John",
"status": "married"
}
]
Here is my wrapper
@XmlRootElement(name = "users")
public class UserListWrapper {
private List<User> users;
@XmlElement(name = "user")
public List<User> getUsers() {
return users;
}
// getters and setters omitted
}
And User class
@XmlRootElement
class User {
private String name;
private String status;
// getters and setters omitted
}
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
When I send
{
"user": [
{
"name": "Bob",
"status": "single"
},
{
"name": "Mike",
"status": "married"
}
]
}
all works fine. But I need this format
[
{
"name": "Bobby",
"status": "single"
},
...
]
UPD
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);
回答1:
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).
UPDATE
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>>(){});
See this related post
UPDATE 2
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>>(){});
来源:https://stackoverflow.com/questions/27643482/how-to-create-proper-jaxb-mapping-to-make-jersey-deserialization-process-happene