繁体   English   中英

将json字符串转换为java对象

[英]Convert json String to java object

我有以下 jsonString,我需要将它转换为 java 对象,我使用以下代码来转换它,但我得到了这个异常

com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.innvo.web.rest.dto.Responsedetail$Questiongroup]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)

JSON 字符串

String jsonStrings ="{"questiongroups":[{"questiongroup":"1000","questions":[{"question":1001,"response":4},{"question":1002,"subquestion":1001,"response":"A2"}]}]}";

响应详细信息.java

public class Responsedetail {

@JsonProperty("questiongroups")
public List<Questiongroup> questiongroups;

public List<Questiongroup> getQuestiongroups() {
    return questiongroups;
}

public void setQuestiongroups(List<Questiongroup> questiongroups) {
    this.questiongroups = questiongroups;
}

public Responsedetail() {
    super();
}



class Questiongroup{

    @JsonProperty("questiongroup")
    String questiongroup;
    @JsonProperty("questions")
    List<Question> questions;

    public Questiongroup() {
        super();
    }

    public String getQuestiongroup() {
        return questiongroup;
    }

    public void setQuestiongroup(String questiongroup) {
        this.questiongroup = questiongroup;
    }

    public List<Question> getQuestions() {
        return questions;
    }

    public void setQuestions(List<Question> questions) {
        this.questions = questions;
    }
    class Question{

        @JsonProperty("question")
        String question;
        @JsonProperty("response")
        String response;
        public Question() {
            super();
        }
        public String getQuestion() {
            return question;
        }
        public void setQuestion(String question) {
            this.question = question;
        }
        public String getResponse() {
            return response;
        }
        public void setResponse(String response) {
            this.response = response;
        }       
    }
}   

}

转换代码

String jsonStrings ="{"questiongroups":[{"questiongroup":"1000","questions":[{"question":1001,"response":4},{"question":1002,"subquestion":1001,"response":"A2"}]}]}";

ObjectMapper mapper = new ObjectMapper();

    Responsedetail responsedetail = mapper.readValue(response.getDetails(), Responsedetail.class);

    System.out.println(responsedetail);
    System.out.println(responsedetail.questiongroups);

您的Questiongroup类嵌套在Responsedetail类中,而Question嵌套在Questiongroup

由于您没有将它们static ,因此它们是内部类

向嵌套类添加static以使其成为静态嵌套类

或者,在它们自己的.java源文件中将它们全部.java顶级类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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