how to parse json array value using json node

前端 未结 1 1206
南方客
南方客 2021-01-15 04:47

I have a JsonNode which contains the following JSON. Inside that JsonNode object is an array. In that array there are three fields, one of which, <

相关标签:
1条回答
  • 2021-01-15 05:20

    The easiest way I can see is creating POJO classes which fit to your 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 + "]";
        }
    }
    

    Simple usage:

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

    Above program prints:

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

    If you want to use JsonNode you can do it in this way:

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

    Above program prints:

    ["53637cc144ae8b607e089701"]
    "Red"
    "r1"
    ["53637d1844ae8b607e089704"]
    "Amber"
    "a1"
    ["53637eac44ae8b607e089706"]
    "Green"
    "g1"
    
    0 讨论(0)
提交回复
热议问题