簡體   English   中英

傑克遜JSON在反序列化時例外

[英]Jackson JSON exception at deserialization

我有問題使用Jackson庫來反序列化JSON字符串並將其映射到POJO

我有這個json:

[{
    "requestor": "Nick Jagger",
    "smtp": "test@email.com",
    "smtp_from": "test2@email.com",
    "cnname": "testcn",
    "date": "2014-11-11",
    "system_ciid": "3926598",
    "request_base64": "its some base64 hash"
}, {
    "requestor": "Freddie Mercury",
    "smtp": "test@email.com",
    "smtp_from": "test2@email.com",
    "cnname": "testowe cn",
    "date": "2014-11-26",
    "system_ciid": "JK19",
    "request_base64": "some base64 hash"
}]

我創建了POJO類來表示此數組中的一個元素:

public class Questionareimplements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @JsonProperty("cnname")
    private String caName;
    @JsonProperty("smtp")
    private String smtp;
    @JsonProperty("requestor")
    private String issuer;
    @JsonProperty("system_ciid")
    private String system_ciid;
    @JsonProperty("date")
    private String date;
    @JsonProperty("request_base64")
    private String base64String;
    @JsonProperty("smtp_from")
    private String smtp2;


    // getters and setters
}

還有一個表示這些對象列表的類:

public class QuestionareList {

    private List<Questionare> questionares;

    public List<Questionare> getQuestionares() {
        return questionares;
    }

    public void setQuestionares(List<Questionare> questionares) {
        this.questionares = questionares;
    }
}

現在我如何映射這些

QuestionareList listQ = new QuestionareList();

ObjectMapper m = new ObjectMapper();

listQ = m.readValue(jsonString,QuestionareList.class);

我得到的只是:

Can not deserialize instance of com.test.service.QuestionareList out of START_ARRAY token
 at [Source: java.io.StringReader@27d525; line: 1, column: 1]

知道我做錯了什么嗎?

我在考慮你已經有2個罐子,即1. Jackson Core 2. Jackson Mapper

因此,從JSON解析到您的POJO

ObjectMapper mapper = new ObjectMapper();
JavaType javaType=mapper.getTypeFactory().constructCollectionType(List.class,Questionare.class);

QuestionareList listQ = new QuestionareList();
listQ.setQuestionares(mapper.readValue(jsonString,javaType));

或者,如果我們能以你的方式做到這一點

    ObjectMapper mapper = new ObjectMapper();
    JavaType javaType=mapper.getTypeFactory().constructType(QuestionareList.class);

    QuestionareList listQ = new QuestionareList();
    listQ = mapper.readValue(jsonString,javaType);

就是這樣!

QuestionareList需要json對象,它有數組字段,但你的json字符串只是一個數組。 您可以使用以下命令將數組反序列化為List List questionares = m.readValue(jsonString,new TypeReference>(){});

暫無
暫無

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

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