I am writing a POST API where I need to form a payload as,
{
"questions":{
"preferredAnswer":{
answer[0]:"my first answer",
answer[1]:"second answer"
}
}
This needs to be mapped as a java object.
My questions is, Is there a way I can map this json to the below class? or Can I declare answers variable as String answer[0]; String answer[1];
(This syntax is not allowed)
public Class Questions {
PreferredAnswer preferredAnswer;
}
public Class PreferredAnswer {
String[] answers;
}
How could I map the json?
You can't declare variable with square brackets, however you can have your JSON property with brackets and map it using @JsonProperty
annotation as below
public Class PreferredAnswer {
@JsonProperty("answer[0]")
private String answer0;
@JsonProperty("answer[1]")
private String answer1;
}
Note: You need to provide setter/getter for these private properties.
This will map your JSON into java object and vice versa.