Flatten a JSON string to make the key including each level key value to Map using Gson or Jackson

前端 未结 2 756
醉梦人生
醉梦人生 2021-01-19 05:42

I have an enhanced question regarding Flatten a JSON string to Map using Gson or Jackson.

My scenario included duplicated keys, so the solution in the above questio

2条回答
  •  感情败类
    2021-01-19 06:38

    You can get the JSON as JsonNode and go through all fields recursively and add key and value field to a Map. When a value is an object instead of string you can add the field name to List to be joined with periods when a string is finally encountered. First create (for readability) a separate method that add Json fields to a Map:

    void mapAppender(Map result, Entry node, List names) {
        names.add(node.getKey());
        if (node.getValue().isTextual()) {
            String name = names.stream().collect(joining("."));
            result.put(name, node.getValue().asText());
        } else {
            node.getValue().fields()
                .forEachRemaining(nested -> mapAppender(result, nested, new ArrayList<>(names)));
        }
    }
    

    and use it like this:

    ObjectMapper mapper = new ObjectMapper();
    Map result = new HashMap<>();
    mapper.readTree(json).fields()
        .forEachRemaining(node -> mapAppender(result, node, new ArrayList()));
    

    Where fields() returns an Iterator. Beware of StackOverflowErrors and perhaps low performance for deeply nested JSON.

提交回复
热议问题