简体   繁体   中英

How to read array of values from Json dynamically using Jackson Streaming API?

I am new to Jackson Streaming API.

I want to read array of values from the following JSON object dynamically.

{
    "jsonAry": [
        {
            "key1": "val1",
            "key2": "val2"
        },
        {
            "key3": "val3",
            "key4": "val4"
        }
    ]
}

After reading this article you can deserialize it in this way:

ObjectMapper mapper = new ObjectMapper();
JsonFactory f = new JsonFactory();
JsonParser jp = f.createParser(JSON);
//Skip all tokens before start array token.
while (jp.nextToken() != JsonToken.START_ARRAY) {
}
MapType mapType = mapper.getTypeFactory().constructMapType(Map.class, String.class, String.class);
while (jp.nextToken() != JsonToken.END_ARRAY) {
    Map<String, String> map = mapper.readValue(jp, mapType);
    System.out.println(map);
}

Next option is to use JsonNode :

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(JSON);
JsonNode arrayNode = rootNode.get("jsonAry");
Iterator<JsonNode> jsonNodeIterator = arrayNode.elements();
while (jsonNodeIterator.hasNext()) {
    JsonNode itemNode = jsonNodeIterator.next();
    Iterator<String> fieldNames = itemNode.fieldNames();
    while (fieldNames.hasNext()) {
        String field = fieldNames.next();
        System.out.println(field + " = " + itemNode.get(field));
    }
}

If your JSON is not big, you can deserialize it to POJO s. Example:

class JsonRoot {

    @JsonProperty("jsonAry")
    private List<JsonEntity> entities;

    public List<JsonEntity> getEntities() {
        return entities;
    }

    public void setEntities(List<JsonEntity> entities) {
        this.entities = entities;
    }

    @Override
    public String toString() {
        return "JsonRoot{" +
                "entities=" + entities +
                '}';
    }
}

class JsonEntity {

    private Map<String, String> values = new LinkedHashMap<String, String>();

    public Map<String, String> getValues() {
        return values;
    }

    @JsonAnySetter
    public void setValues(String key, String value) {
        values.put(key, value);
    }

    @Override
    public String toString() {
        return "JsonEntity{" +
                "values=" + values +
                '}';
    }
}

And deserializing is looking like this:

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue(JSON, JsonRoot.class));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM