javajsonspringdto

name problem mapping JSON parameters to class DTO in spring boot


I have a class in JAVA of type DTO that maps an input paramter of type JSON. This works for field names in the DTO that match those in the JSON (es. latitude) but different ones (java name convention and json name convention) the data is of type null (i.e. startDate). I have tried various soliations, suggested online, such as using the @JsonProperty annotation but to no avail.

My JSON input:

{
    "latitude": 52.52,
    "longitude": 13.41,
    "start_date": "2023-05-08",
    "end_date": "2023-05-22"
}

My DTO class:

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Builder
public class InputParametersDTO {

    private float latitude;
    private float longitude;
    @JsonProperty("start_date")
    private String startDate;
    @JsonProperty("end_date")
    private String endDate;
    
}

My Controller:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;

@RestController
@RequestMapping("api/v1/demo")
public class OpenMeteoController {


    @GetMapping
    @ResponseBody
    public ResponseEntity<?> getData(InputParametersDTO inputParametersDTO) throws Exception
    {
        float lat = inputParametersDTO.getLatitude(); // 52.52
        String endDate = inputParametersDTO.getEndDate(); // null
// DO OTHER STUFF

    }

}

Solution

  • try below, working for me.

    import com.fasterxml.jackson.annotation.JsonProperty;
    import lombok.*;
    
    @AllArgsConstructor
    @NoArgsConstructor
    @Getter
    @Setter
    @Builder
    public class InputParametersDTO {
    
        private float latitude;
        private float longitude;
        @JsonProperty(value = "start_date")
        private String startDate;
        @JsonProperty(value = "end_date")
        private String endDate;
        
    }