简体   繁体   English

如何使用Jackson将JSON数组反序列化为Java对象

[英]How to use Jackson to deserialize a JSON Array into java objects

I have a JSON array 我有一个JSON数组

{ "inList" : 
    [
        { "cmd" : "enqueue", "name" : "job1", "pri" : 4 }, 
        { "cmd" : "enqueue", "name" : "job2", "pri" : 3 },
        { "cmd" : "dequeue" },
        { "cmd" : "enqueue", "name" : "job3", "pri" : 0 },
        { "cmd" : "enqueue", "name" : "job4", "pri" : 1 },
        { "cmd" : "dequeue" }
    ]
}

I would like to use the powerful jackson to de serialize the JSON into java object. 我想使用功能强大的杰克逊将JSON反序列化为Java对象。

And I have the hit class (I think it has something wrong) 我有热门课程(我认为这有问题)

public class InList {
    private String[] inList;
    private LinkedList<Object> jobs;

    public InList() { }

    public String[] getInList() {
        return inList;
    }

    public void setInList(String[] inList) {
        this.inList = inList;
    }

    public LinkedList<Object> getJobs() {
        return jobs;
    }

    public void setJobs(LinkedList<Object> jobs) {
        this.jobs = jobs;
    }
}

And when I try to de serialize the JSON, it just can not hit the class 当我尝试取消序列化JSON时,无法击中该类

ObjectMapper mapper = new ObjectMapper();

InList inList = null;
try {
    inList = mapper.readValue(jsonStr, InList.class);
}

Could you help me figure out? 你能帮我弄清楚吗?

Thanks! 谢谢!

Your bean class should be like below:- 您的bean类应如下所示:

 import java.util.List;
 import org.codehaus.jackson.annotate.JsonProperty;
 public class InList {  
@JsonProperty("inList")
private List<InListDetail> inList;
public List<InListDetail> getInList() {
    return inList;
}
public void setInList(List<InListDetail> inList) {
    this.inList = inList;
}
}

import org.codehaus.jackson.annotate.JsonProperty;
public class InListDetail { 
@JsonProperty("cmd")
private String cmd;
@JsonProperty("name")
private String name;
@JsonProperty("pri")
private int pri;
public String getCmd() {        
       return cmd;
}
public void setCmd(String cmd) {
    this.cmd = cmd;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}

public int getPri() {
    return pri;
}

public void setPri(int pri) {
    this.pri = pri;
}

}

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

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