将json String转换为java对象

时间:2016-10-01 11:59:31

标签: java json jackson objectmapper

我有以下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

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

1 个答案:

答案 0 :(得分:2)

您的Questiongroup课程嵌套在Responsedetail课程中,Question嵌套在Questiongroup内。

由于您没有制作static,因此 inner classes

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

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