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

时间:2017-10-02 22:03:42

标签: java json serialization jackson

我有一个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" }
    ]
}

我想使用强大的jackson将JSON序列化为java对象。

我有热门课程(我觉得它有些不对劲)

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

当我尝试对JSON进行序列化时,它就无法上课

ObjectMapper mapper = new ObjectMapper();

InList inList = null;
try {
    inList = mapper.readValue(jsonStr, InList.class);
}
你可以帮我解决一下吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您的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;
}

}