Home > other >  I am trying to create an API using SpringBoot but I don't know how to handle json request/respo
I am trying to create an API using SpringBoot but I don't know how to handle json request/respo

Time:11-17

I am new to Java and Spring boot. I am creating a new API. Using postman I am sending a request body which contains request header and request payload.

enter image description here

Then I have a controller which handles the request with the help of RequestPayload class. (And a service and dao file but I am sure those are ok.)

Kindly let me know what Am I missing here or what do I not know.

public class RequestPayload {

    String pol_pkg_prod_code;
    JSONObject checklist;
    
    public JSONObject getCheckList() {
        return checklist;
    }
    public void setCheckList(JSONObject checklist) {
        this.checklist = checklist;
    }
    public String pol_pkg_prod_code() {
        return pol_pkg_prod_code;
    }
    public void setpol_pkg_prod_code(String pol_pkg_prod_code) {
        this.pol_pkg_prod_code = pol_pkg_prod_code;
    }

CodePudding user response:

You need a POJO class that will match the structure of your JSON payload, actually a few nested classes. Spring will automatically parse JSON into this POJO.

public class Request {
    private RequestPayload reqPayload;
    // Getter Setter
}

public class RequestPayload {
    private Checklist checklist;
    // Getter Setter
}

public class RequestPayload {
    @JsonProperty("pol_pkg_prod_code")
    private String polPkgProdCode;
}

Then add it to Controller as an argument like this:

@RequestBody Request request

This tutorial explains it well https://www.baeldung.com/spring-request-response-body

  • Related