I am using Spring web service and in my controller I am using @RequestBody and @ResponseBody. Now from what I understand these annotations do the magic of converting the incoming request to the class object that you specify. However, what if my class object had references to other class objects. Something like:
public class Question {
private String questionText;
List<Options> options;
public String getQuestionText() {
return questionText;
}
public void setQuestionText(String questionText) {
this.questionText = questionText;
}
//getters and setters for options
}
The incoming request can look something like this:
{"questionText":"sample question","options":{"option-0":"option0","option-1":"option1","option-2":"option2","option-3":"option3"}}
Option looks something like this:
public class Option {
private String option;
public String getOption() {
return option;
}
public void setOption(String option) {
this.option = option;
}
}
How can will this be mapped?
This is absolutely not an issue. Jackson, which Spring uses, can extract that information to produce the appropriate JSON.
Your
Question
class acts as the template for the root JSON. So the JSON object will have a field calledquestionText
which will be a JSON String and a field calledoptions
which will be a JSON array with JSON objects in it that follow theOptions
template.Consequently, this
is invalid.
options
must be a JSON array and the elements must be JSON objects, not JSON strings.It would have to look like
to match your
Options
class.Knowing that Spring uses Jackson, you can test this relatively easily
produces