【问题标题】:Convert json String to java object将json字符串转换为java对象
【发布时间】:2016-10-01 11:59:30
【问题描述】:

我有以下 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"}]}]}";

ResponseDetails.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);

【问题讨论】:

    标签: java json jackson objectmapper


    【解决方案1】:

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

    由于您没有将它们设为static,因此它们是inner classes

    static 添加到嵌套类中,使其成为静态嵌套类

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

    【讨论】:

    • 谢谢,你帮了我,节省了我的时间
    猜你喜欢
    • 2011-08-30
    • 1970-01-01
    • 2017-03-24
    • 2021-09-18
    • 2011-02-02
    • 2015-05-24
    • 2011-08-15
    • 2012-01-22
    • 2011-06-19
    相关资源
    最近更新 更多