2014-05-06 68 views
1

我有一個JsonNode其中包含以下JSON。裏面那個JsonNode對象是一個數組。在該陣列中有三個字段,其中一個是slaid,是一個列表。另外兩個是字符串。這是JSON。如何使用json節點解析json數組值

{ 
    "SLA": [ 
     { 
      "slaid": [ 
       "53637cc144ae8b607e089701" 
      ], 
      "ragindicator": "Red", 
      "name": "r1" 
     }, 
     { 
      "slaid": [ 
       "53637d1844ae8b607e089704" 
      ], 
      "ragindicator": "Amber", 
      "name": "a1" 
     }, 
     { 
      "slaid": [ 
       "53637eac44ae8b607e089706" 
      ], 
      "ragindicator": "Green", 
      "name": "g1" 
     } 
    ] 
} 

我想分析該值。我該如何解析它,slaid的型號是List<String>?我嘗試了一些方法,但我仍然無法找到解決方案。

+3

顯示你已經嘗試過的方式。 –

+1

「解析這個值」是什麼意思?你想用_what_值做什麼? – fge

+0

我使用迭代器,jsonNode.iterator()但我得到一個空的迭代器 –

回答

7

我能看到的是創造POJO類,其適合您的JSON最簡單的方法:

class Slaids { 

    @JsonProperty("SLA") 
    private List<Slaid> slaids; 

    public List<Slaid> getSlaids() { 
     return slaids; 
    } 

    public void setSlaids(List<Slaid> slaids) { 
     this.slaids = slaids; 
    } 

    @Override 
    public String toString() { 
     return slaids.toString(); 
    } 
} 

class Slaid { 

    private List<String> slaid; 
    private String ragindicator; 
    private String name; 

    public List<String> getSlaid() { 
     return slaid; 
    } 

    public void setSlaid(List<String> slaid) { 
     this.slaid = slaid; 
    } 

    public String getRagindicator() { 
     return ragindicator; 
    } 

    public void setRagindicator(String ragindicator) { 
     this.ragindicator = ragindicator; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    @Override 
    public String toString() { 
     return "Slaid [slaid=" + slaid + ", ragindicator=" + ragindicator + ", name=" + name + "]"; 
    } 
} 

簡單的用法:

ObjectMapper mapper = new ObjectMapper(); 
System.out.println(mapper.readValue(json, Slaids.class)); 

上面的程序打印:

[Slaid [slaid=[53637cc144ae8b607e089701], ragindicator=Red, name=r1], Slaid [slaid=[53637d1844ae8b607e089704], ragindicator=Amber, name=a1], Slaid [slaid=[53637eac44ae8b607e089706], ragindicator=Green, name=g1]] 

如果您想用JsonNode就可以這樣做:

ObjectMapper mapper = new ObjectMapper(); 
JsonNode rootNode = mapper.readTree(json); 
ArrayNode slaidsNode = (ArrayNode) rootNode.get("SLA"); 
Iterator<JsonNode> slaidsIterator = slaidsNode.elements(); 
while (slaidsIterator.hasNext()) { 
    JsonNode slaidNode = slaidsIterator.next(); 
    System.out.println(slaidNode.get("slaid")); 
    System.out.println(slaidNode.get("ragindicator")); 
    System.out.println(slaidNode.get("name")); 
} 

上面的程序打印:

["53637cc144ae8b607e089701"] 
"Red" 
"r1" 
["53637d1844ae8b607e089704"] 
"Amber" 
"a1" 
["53637eac44ae8b607e089706"] 
"Green" 
"g1"