如何将ClientResponse实体正确反序列化为POJO列表

时间:2014-11-07 15:17:11

标签: java json jersey jackson

我试图将响应实体反序列化为POJO列表。当我直接这样做时,使用像这样的GenericType:

private List<UserRole> extractMembersDirectly(final ClientResponse response) {
    return response.getEntity(new GenericType<List<UserRole>>() {});
}

我得到了这个例外:

com.sun.jersey.api.client.ClientHandlerException: com.fasterxml.jackson.databind.JsonMappingException: Unexpected token (START_OBJECT), expected VALUE_STRING: need JSON String that contains type id (for subtype of java.util.List)

但是,当我直接使用ObjectMapper时,我可以成功反序列化:

private List<UserRole> extractMembersUsingMapper(final ClientResponse response) throws IOException {
    String json = response.getEntity(String.class);
    ObjectMapper mapper = new ObjectMapperFactory().build();
    return mapper.readValue(json, new TypeReference<List<UserRole>>() {});
}

POJO只是:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonSnakeCase
public class UserRole {
    private UUID id;

    public UserRole(@JsonProperty("id") final UUID id) {
        this.id = id;
    }

    public UUID getId() {
        return id;
}

有没有办法直接从实体反序列化而不先反序列化为String?

1 个答案:

答案 0 :(得分:0)

您可以尝试在类本身上使用自定义序列化程序

编写序列化程序

   public class UserRoleSerializer extends JsonSerializer<Item> {
      @Override
      public void serialize(UserRole userRole, JsonGenerator jgen, SerializerProvider      provider) throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeStringField("id", userRole.id);
    jgen.writeEndObject();
  }
}

现在将序列化程序注册到您的班级

     @JsonSerialize(using = UserRoleSerializer.class)
     public class UserRole {
         ...
      }

然后只是一个想法,不确定那就是你要找的东西