簡體   English   中英

帶有Jersey REST服務的字符串列表的POST JSON問題

[英]Issue with POST JSON with list of strings to a Jersey REST service

我是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?"
}

Question類具有三個字段(字符串代表問題,字符串代表正確答案,字符串列表代表可能的答案):

@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);
}

}

找到解決方案后,我將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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM