这将是以下问题的扩展:
Spring web service request and response for mapping having list of other objects
如果Question POJO具有枚举类型怎么办。当发出请求并使用@RequestBody时,如何在ajax调用中表示这一点。
例如:
public class Question {
private String questionText;
List<Options> options;
private QuestionTye questionType
public String getQuestionText() {
return questionText;
}
public void setQuestionText(String questionText) {
this.questionText = questionText;
}
//getters and setters for options
}
枚举如下所示:
public enum QuestionType {
MCQ, FILL_IN_THE_BLANK, QUESTION_AND_ANSWER, MATCH_THE_FOLLOWING
}
在将JSON发送到服务器时,应该如何格式化JSON?
最佳答案
假设您在classpatch上具有jackson API,请添加带注释的“创建”方法。我还想向枚举添加“ None”选项以避免空指针:
public enum QuestionType {
MCQ, FILL_IN_THE_BLANK, QUESTION_AND_ANSWER, MATCH_THE_FOLLOWING, NONE;
@JsonCreator
public QuestionType create(String input){
QuestionType result;
if("MCQ".equals(input)){
result = MCQ;
}
else if(/*snip etc*/){
}//etc
else{
result = NONE;//Or null or throw an exception .. whatever
}
return result;
}
}