简体   繁体   中英

Spring get request to Object mapping customisation ways

I would LIke to know how can I map the Spring Controller GET request to my Object.

I have a situation I have both GET and POST requests enabled for a single search api.

I am receiving my POST api as JSON data type and which uses

CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES

strategy to convert the json to my object.

Which will convert a field say date_to to dateTo in my Java modal.

But if I receive the same request over GET I need to pass dateTo instead of date_to. Which makes lots of confusion for the end user.

I was looking for something like below

class MySearchRequestDTO{
    private int start = 0;
    private int count = 10;

    @RequestAttribute(name="date_from")
    private Date dateFrom;

    @RequestAttribute(name="date_to")
    private Date dateTo;

    //Getters and Setters
}

Controller Class

@RequestMapping(value = "/search", method = {RequestMethod.GET})
public ApiSuccessResponse aSearchGet(MySearchRequestDTO request) throws IMSException{
    return new ApiSuccessResponse(inventoryService.aSearch(request));
}

@RequestMapping(value = "/search", method = {RequestMethod.POST})
public ApiSuccessResponse aSearchPost(@RequestBody MySearchRequestDTO request) throws IMSException{
    return new ApiSuccessResponse(inventoryService.aSearch(request));
}

What is the best way to follow the same name strategy across my application url types in this case. Let me know if someone solved this problem the better way.

Thanks a lot for the time for reading this.

Spring use Jackson mapper for mapping json to object and vice versa. With Jackson You are able to implement own version of mapper for concrete class, so just write your own implementation of serializer and deserializer for classes you need.

Since spring using jackson, following method works.

public class MySearchRequestDTO {
    int test;

    @JsonProperty("t")
    public int getTest() {
      return test;
    }

    @JsonProperty("t")
    public void setTest(int test) {
      this.test = test;
    }
}

Then:

MySearchRequestDTO c = new MySearchRequestDTO();
c.setTest(5);

ObjectMapper mapper = new ObjectMapper();
System.out.println("Serialization: " + mapper.writeValueAsString(c));

MySearchRequestDTO r = mapper.readValue("{\"t\":25}",MySearchRequestDTO.class);
System.out.println("Deserialization: " + r.getTest());

Result:

Serialization: {"t":5}
Deserialization: 25

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM