Home > database >  How to get from HttpResponse java object class?
How to get from HttpResponse java object class?

Time:11-13

I have a method that receives a HttpResponse.He receives a response from the server in the form of a 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;
}

In a variable response i have json.Now I need to somehow convert this JSON into 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   '\''  
            '}';
}
}

Tell me how to get from HttpResponse and serialize it into PostDTO?I do not understand what needs to be written to convert HttpResponse in PostDTO.

CodePudding user response:

Have you heard about Gson?

Add Gson to your depndencys: https://search.maven.org/artifact/com.google.code.gson/gson/2.8.9/jar

And you can simply do this:

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

If you want to know more about it: https://www.baeldung.com/gson-deserialization-guide

  • Related