我是Jersey REST服务的新手,目前我正在使用POSTMAN发布带有字符串列表的JSON,但目前还没有任何成功。
我想发布的JSON是一个Question对象:
{
"answers":["I don't know","Maybe","No","Yes"],
"correct":"Yes",
"question":"Are you learning Android?"
}
Post方法正在使用Question对象,将正确答案设置为“CORRECT”并将Question对象生成为JSON:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("add")
public Question getAllItems(Question question) {
question.setCorrect("CORRECT");
return question;
}
因此,当我通过Postamn发布JSON时,我收到的JSON没有我发送的字符串列表,因为它应该:
{
"correct":"CORRECT",
"question":"Are you learning Android?"
}
我期望由REST服务生成的JSON:
{
"answers":["I don't know","Maybe","No","Yes"],
"correct":"CORRECT",
"question":"Are you learning Android?"
}
问题类有三个字段(字符串表示问题,字符串表示正确的答案,字符串列表表示可能的答案):
@XmlRootElement
public class Question {
private String question;
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
private List<String> answers;
@XmlElement
public List<String> getAnswers() {
return answers;
}
public void setAnswers(List<String> answers) {
if(this.answers == null){
this.answers = new ArrayList<>();
}
this.answers.clear();
this.answers.addAll(answers);
Collections.shuffle(this.answers);
}
public void setAnswers(String[] answers) {
if(this.answers == null){
this.answers = new ArrayList<>();
}
this.answers.clear();
this.answers.addAll(Arrays.asList(answers));
Collections.shuffle(this.answers);
}
private String correct;
public String getCorrect() {
return correct;
}
public void setCorrect(String correct) {
this.correct = correct;
}
public Question() {}
public Question(String question, List<String> answers, String correct){
this.question = question;
this.correct = correct;
this.answers = new ArrayList<>(answers);
}
public Question(String question, String[] answers, String correct){
this.question = question;
this.correct = correct;
this.answers = new ArrayList<>();
setAnswers(answers);
}
}
答案 0 :(得分:0)
找到解决方案,我更改了getAnswers以返回String []而不是List,并且它有效。
@XmlElement
public String[] getAnswers() {
String[] temp = new String[answers.size()];
for(int i = 0; i < temp.length; i++){
temp[i] = answers.get(i);
}
return temp;
}