2017-10-02 4 views
0

J'ai un tableau JSONComment utiliser Jackson désérialiser un tableau JSON en objets java

{ "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" } 
    ] 
} 

Je voudrais utiliser le puissant jackson de de sérialisation JSON en objet java.

Et j'ai la classe de coup (je pense qu'il a quelque chose de mal)

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

Et quand je tente de de sérialisation JSON, il ne peut tout simplement pas frapper la classe

ObjectMapper mapper = new ObjectMapper(); 

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

pourrait vous m'aidez à comprendre?

Merci!

+1

Votre JSON décrit un champ 'inList' qui contient un tableau d'objets. La classe a et le champ 'inList' qui est une liste de' String'. – teppic

+0

À quoi l'objet résultant ressemblerait-il? – shmosel

+0

Vous avez réellement un objet JSON. Le tableau est à l'intérieur –

Répondre

0

Votre classe de haricot devrait être comme ci-dessous: -

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

}