How to create proper JAXB mapping to make Jersey deserialization process happened

拜拜、爱过 提交于 2019-12-11 06:29:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!