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

核能气质少年 提交于 2020-01-16 20:33:28

问题


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?


回答1:


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"}]}


来源:https://stackoverflow.com/questions/22186934/spring-web-service-request-and-response-for-mapping-having-list-of-other-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!