Semicolon
Semicolon

Reputation: 141

How to use Jackson to deserialize a JSON Array into java objects

I have a JSON array

{ "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.

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

ObjectMapper mapper = new ObjectMapper();

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

Could you help me figure out?

Thanks!

Upvotes: 0

Views: 1240

Answers (1)

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5581

Your bean class should be like below:-

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

}

Upvotes: 1

Related Questions