如何从 HttpResponse java 对象 class 获取?

How to get from HttpResponse java object class?

我有一个接收 HttpResponse.He 的方法以 JSON 的形式从服务器接收响应。

 public static PostDTO getRequest(String url, String path) {
   
    HttpResponse<JsonNode> response = Unirest.get(url + path).asJson();
    postDTO.setStatus(response.getStatus());
    /*
     Here I have to write code that makes from HttpResponse<JsonNode> 
     response PostDTO
    */
    return postDTO;
}

在可变响应中我有 json.Now 我需要以某种方式将此 JSON 转换为 PostDTO。

public class PostDTO {

private int status;
private List<PostPojo> posts;

public int getStatus() {
    return status;
}

public void setStatus(int status) {
    this.status = status;
}

public List<PostPojo> getPosts() {
    return posts;
}

public void setPosts(List<PostPojo> posts) {
    this.posts = posts;
}
}

PostPojo class

public class PostPojo {

private int userId;
private int id;
private String title;
private String body;

public PostPojo() {
}

public PostPojo(int userId, int id, String title, String body) {
    this.userId = userId;
    this.id = id;
    this.title = title;
    this.body = body;
}

public int getUserId() {
    return userId;
}

public void setUserId(int userId) {
    this.userId = userId;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getBody() {
    return body;
}

public void setBody(String body) {
    this.body = body;
}


@Override
public String toString() {
    return "PostModel{" +
            "userId=" + userId +
            ", id=" + id +
            ", title='" + title + '\'' +
            ", body='" + body + '\'' +
            '}';
}
}

告诉我如何从HttpResponse中获取并序列化成PostDTO?我不明白在PostDTO中转换HttpResponse需要写什么。

你听说过 Gson 吗?

将 Gson 添加到您的依赖项中:https://search.maven.org/artifact/com.google.code.gson/gson/2.8.9/jar

你可以简单地这样做:

Gson gson = new GsonBuilder().create();
HttpEntity entity = response.getEntity();
String jsonString = EntityUtils.toString(entity);
PostDTO postDTO = gson.fromJson(jsonString, PostDTO.getClass());

如果您想了解更多:https://www.baeldung.com/gson-deserialization-guide