我的 REST 服务响应以下数据:
[
{
"name": "Bart",
"age": 10
},
{
"name": "Homer",
"age": 42
},
{
"name": "Marjorie",
"age": 34
}
]
结果集是一个对象数组,我想用 Google 的 HTTP 客户端库自动解析这些对象。因此我创建了一个SimpsonResult
和Simpson
类:
辛普森结果.java
public class SimpsonResult {
private List<Simpson> simpsons;
public SimpsonResult() {
}
public List<Simpson> getSimpsons() {
return simpsons;
}
public void setSimpsons(List<Simpson> simpsons) {
this.simpsons = simpsons;
}
}
辛普森.java
public class Simpson {
@Key
private String name;
@Key
private int age;
public Simpson() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
现在我想查询我的后端并自动将响应映射到SimpsonResult
. 因此,我编写了以下代码:
@Override
public SimpsonResult loadDataFromNetwork() throws IOException {
HttpRequestFactory requestFactory = getHttpRequestFactory();
GenericUrl url = new GenericUrl(baseUrl);
HttpRequest request = requestFactory.buildGetRequest(url);
request.setParser(new JacksonFactory().createJsonObjectParser());
return request.execute().parseAs(SimpsonResult.class);
}
但是当我执行代码时,我会从com.google.api.client.json.JsonParser
.
当我将它映射到一个字符串 ( request.execute().parseAsString()
) 时,它就可以工作了。
所以我认为我的映射声明是错误的?