我必须制作一个 jar 来访问 API 来获取人员详细信息列表,该列表基本上有四个字段:id、姓名、薪水、部门。
我正在使用 apache httpclient 执行 get 请求,该请求在点击 API 时为我提供了一个 httpentity。
httpentity提供了一个方法来获取response的内容,但它返回的是inputstream。
在通过 inputreader 读取此输入流并将其打印出来时,我确认它为我提供了个人详细信息列表。
但我不知道如何将其转换为人员详细信息列表。
那是 PersonDetails 对象:-
public class PersonDetails {
private UUID id;
private String name;
private String department;
private Integer salary;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
@Override
public String toString() {
return "PersonDetails{" +
"id=" + id +
", name='" + name + '\'' +
", department='" + department + '\'' +
", salary=" + salary +
'}';
}
}
这是我的 GetRequest 代码:-
public static void main(String[] args) {
List<PersonDetails> personDetails = new ArrayList<>();
HttpClient httpClient = HttpClientBuilder.create().build();
String url = "/api/person-details";
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream content = httpEntity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
}
我想将此内容转换为人员详细信息列表。
有人可以帮助我吗?
我听说过杰克逊,但我不知道如何使用它。
首先我创建一个默认集合类型
CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(List.class, PersonDetails.class);
List<PersonDetails> personDetails = mapper.readValue(content,collectionType);
其中内容是输入流。
我在某人的博客上找到的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)