我尝试将我的Resteasy REST客户端(3.0.8)切换为使用代理机制,因为这看起来对我很好。我可以成功触发REST请求,但现在我需要映射/反序列化响应。代码如下:
RestRequest.java:
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://127.0.0.1:8080/backend-1.0-SNAPSHOT/");
CategoryClient categoryClient = target.proxy(CategoryClient.class);
categoryList = categoryClient.getCategories();
CategoryClient.java(代理接口):
public interface CategoryClient {
@GET
@Path("categories")
@JsonProperty("categories")
@JsonIgnoreProperties(ignoreUnknown = true)
@Produces(MediaType.APPLICATION_JSON)
public List<Category> getCategories();
Category.java(目标模型):
public class Category {
private Long id;
private String name;
private List<Asset> assetList;
// getter & setters
}
JSON回复我得到并需要映射:
{
"_links" : {
"self" : {
"href" : "http://127.0.0.1:8080/backend-1.0-SNAPSHOT/categories{?page,size,sort}",
"templated" : true
},
"search" : {
"href" : "http://127.0.0.1:8080/backend-1.0-SNAPSHOT/categories/search"
}
},
"_embedded" : {
"categories" : [ {
"name" : "monkeys",
"_links" : {
"self" : {
"href" : "http://127.0.0.1:8080/backend-1.0-SNAPSHOT/categories/0"
},
"assetList" : {
"href" : "http://127.0.0.1:8080/backend-1.0-SNAPSHOT/categories/0/assetList"
}
}
}, {
"name" : "donkeys",
"_links" : {
"self" : {
"href" : "http://127.0.0.1:8080/backend-1.0-SNAPSHOT/categories/1"
},
"assetList" : {
"href" : "http://127.0.0.1:8080/backend-1.0-SNAPSHOT/categories/1/assetList"
}
}
}
]
},
"page" : {
"size" : 20,
"totalElements" : 5,
"totalPages" : 1,
"number" : 0
}
}
现在我需要一种机制来将响应映射到List<Category>
,目前只提供
javax.ws.rs.client.ResponseProcessingException: javax.ws.rs.ProcessingException:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of
java.util.ArrayList out of START_OBJECT token
我需要采取哪些步骤才能使映射工作?
答案 0 :(得分:0)
杰克逊注释仅在应用于您反序列化的类时才有效。实现目标的最简单方法是创建一个表示响应结构的类层次结构:
@JsonIgnoreProperties(ignoreUnknown = true)
class Response {
private Embedded embedded;
// getters and setters here
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Embedded {
private List<Category> categories;
// getters and setters here
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Category {
private String name;
// getters and setters here
}
然后您就可以获得类别名称了。我也在寻找转换选项,但似乎不可能。 我发现可能的最好的事情是使用@JsonDeserialize注释重构您的响应:
@JsonDeserialize(converter = ResponseConverter.class)
class Response {
private List<String> categories;
// getters and setters
}
class ResponseConverter implements Converter<Map<String, ?>, Response> {
Response convert(Map<String, ?> jsonInput) {
// convert jsonInput to response and return
}
// implement getInputType and getOutputType methods here
}