I using Spring boot for REST application, I am getting null as DTO object even though the JSON request seems to be correct. Could anyone suggest something.
json from postman
{
"description": "Third questionnaire",
"createdDate": "2022-06-23",
"approvalStatus": "Approved",
"questionnaireVersion": "V1",
"isActive": false,
"questionSet": [
{
"text": "Question text",
"possibleAnswerSet": []
}
]
}
Controller post method is
@PostMapping(
produces = MediaType.APPLICATION_JSON_VALUE ,
consumes = MediaType.APPLICATION_JSON_VALUE
)
public String createQuestionnaire(@RequestBody QuestionnaireDTORequest questionnaireDTORequest){
Questionnaire questionnaire = mapToQuestionnaire(questionnaireDTORequest);
Questionnaire createdQuestionnaire = questionnaireService.createQuestionnaire(questionnaire);
if(createdQuestionnaire != null)
return "Questionnaire created successfully";
else
return "Questionnaire cannot be created";
}
when I run in debug mode i get questionnaireDTORequest as null.
QuestionnaireDTORequest
public class QuestionnaireDTORequest implements Serializable {
private static final long serialVersionUID = 5L;
private String description;
private LocalDate createdDate;
private String approvalStatus;
private String questionnaireVersion;
private boolean isActive = false;
private Set<Question> questionSet = new HashSet<>();
}
CodePudding user response:
TL:DR Add getters and setters to QuestionnaireDTORequest
.
Also, that will only make the values null, not the QuestionnaireDTORequest
object. Is that the case?
I ran:
curl --location --request POST 'localhost:8081/' \
--header 'Content-Type: application/json' \
--data-raw ' {
"description": "Third questionnaire",
"createdDate": "2022-06-23",
"approvalStatus": "Approved",
"questionnaireVersion": "V1",
"isActive": false,
"questionSet": [
{
"text": "Question text" }
]
}'
My controller:
@RestController
public class MyController {
@PostMapping(
produces = MediaType.APPLICATION_JSON_VALUE ,
consumes = MediaType.APPLICATION_JSON_VALUE
)
public String createQuestionnaire(@RequestBody QuestionnaireDTORequest questionnaireDTORequest){
if(questionnaireDTORequest != null)
return "Questionnaire created successfully";
else
return "Questionnaire cannot be created";
}
}
The model was the same only added Getters and Setters.