Home > OS >  Spring - How to convert nested JSON in RequestBody to an entity
Spring - How to convert nested JSON in RequestBody to an entity

Time:02-18

Following is the body of POST request to my endpoint -

{
    "availabilityMap":
    {
        "2021-07-18":["9AM-10AM", "OT"],
        "2021-07-19":["9AM-10AM", "OPD"],
        .
        .
    }
    
}

and following is the skeleton of my controller -

@PostMapping(value = "/appointment", consumes = MediaType.APPLICATION_JSON_VALUE,
        produces= MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity newAppointment(@RequestBody /* WHAT TO PUT HERE?*/) {

}

Can someone please help me define an entity so that the @RequestBody is automatically converted to an entity? Is that possible?

I have tried following a few SO suggestions but could not figure it out yet..

CodePudding user response:

In general, we prepare dto or resource for request and response. If your requests or responses are related to the database, it should be dto, otherwise you should mark it as a resource and you can perform automatic mapping operations using MapStruct.

@Data
public class RequestDto {

    public Map<String, List<String>> availabilityMap;

}

CodePudding user response:

public class RequestVO {

    public Map<String, List<String>> availabilityMap;

    public Map<String, List<String>> getAvailabilityMap() {
        return availabilityMap;
    }

    public void setAvailabilityMap(Map<String, List<String>> availabilityMap) {
        this.availabilityMap = availabilityMap;
    }
}

{} can be represented as an object or a map, and [] can be represented as an implementation class of a Collection. (Commonly used are List and Set, which are also interfaces. The specific classes are specified by the sequence number framework. You can also use implementation classes such as HashMap.) For {}, using an object or a map depends on whether the field is fixed or not. In the example, availabilityMap is a fixed-name field, so the object is used. 2021-07-18 is an indefinite date or other class, so use Map. For one object, if its field is another object, you may need to write a new java class.

  • Related