简体   繁体   中英

Spring web service request and response for mapping having list of other objects

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?

However, what if my class object had references to other class objects.

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 called questionText which will be a JSON String and a field called options which will be a JSON array with JSON objects in it that follow the Options template.

Consequently, this

"options":{"option-0":"option0","option-1":"option1","option-2":"option2","option-3":"option3"}

is invalid. options must be a JSON array and the elements must be JSON objects, not JSON strings.

It would have to look like

"options":[{"option":"option1"}, {"option":"option2"}]

to match your Options class.


Knowing that Spring uses Jackson, you can test this relatively easily

ObjectMapper mapper = new ObjectMapper();
Options o1 = new Options();
o1.setOption("option1");
Options o2 = new Options();
o2.setOption("option2");
Question question = new Question();
question.setOptions(Arrays.asList(o1, o2));
question.setQuestionText("sample question");
System.out.println(mapper.writeValueAsString(question));

produces

{"questionText":"sample question","options":[{"option":"option1"},{"option":"option2"}]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM