javaspringcontroller

How to add a range of values in a Json and return the objects that are in that range


I am trying to create a method in my Controller class to return a list of Locations

I want to give it a range of latitudes and longitudes and return locations that fall in that list.

Currently the Get methon in my controller class looks like

@GetMapping public ResponseEntity<List<Location>> searchLocations(
    @RequestParam(required = false) Location.LocationType type,
    @RequestParam Double lat1, @RequestParam Double lng1, 
    @RequestParam Double lat2, @RequestParam Double lng2,
    @RequestParam(required = false, defaultValue = "10") Integer limit) {
    
    Pageable pageable = PageRequest.of(0, limit);
    List<Location> locations = locationRepository.findByLatBetweenAndLngBetweenAndTypeOrderByTypeDesc(
        Math.min(lat1, lat2), Math.max(lat1, lat2), Math.min(lng1, lng2), Math.max(lng1, lng2), type, pageable);
    
    return ResponseEntity.ok(locations); }

and the data I would pass in is

{
"lat1": 46.6,
"lng1": 46.6, 
"lat2": 48.8, 
"lng2": 48.8,
"type": "premium",
"limit": 3
}

I would like to pass in a Json that looks like

"p1": 46.6, 15.4
"p2": 48.8, 17.5
"type": "premium"
"limit": 3

So the p1 and p2 are points and it returns the locations within those points


Solution

  • Look at @RequestBody for passing a structure, you are currently processing URL parameters.

    @GetMapping
    public ResponseEntity<List<Location>> searchLocations(
        @RequestBody RequestDto requestDto
    ) {
        . . . .
    

    In JSON you can't return values in that way.

    You have to do something like this:

    {
      "p1": {
         "lat": 46.6,
         "lng": 15.4
       },
       "p2": {
         "lat": 48.8,
         "lng": 17.5
        },
        "type": "premium",
        "limit": 3
    }
    

    Or an array of values (which IMHO looks awful):

    {
      "p1": [ 46.6, 15.4 ],
      "p2": [ 48.8, 17.5 ],
      "type": "premium",
      "limit": 3
    }