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

前端 未结 2 753
醉梦人生
醉梦人生 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:37

    I resolved this using below simple code, Only think is need to download jettison and flattener.JsonFlattener library

    import java.util.Map;
    import org.codehaus.jettison.json.JSONObject;
    import com.github.wnameless.json.flattener.JsonFlattener;
    
    public class test {
    
        public static void main(String[] args) {
            String jsonString = "{\"id\" : \"123\",\"name\" : \"Tom\",\"class\" : {\"subject\" : \"Math\",\"teacher\" : \"Jack\"}}";
            JSONObject jsonObject = new JSONObject();
            String flattenedJson = JsonFlattener.flatten(jsonString);
            Map<String, Object> flattenedJsonMap = JsonFlattener.flattenAsMap(jsonString);
            System.out.println(flattenedJsonMap);
        }
    }
    

    Reference link : https://github.com/wnameless/json-flattener

    0 讨论(0)
  • 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<String, String> result, Entry<String, JsonNode> node, List<String> 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<String, String> result = new HashMap<>();
    mapper.readTree(json).fields()
        .forEachRemaining(node -> mapAppender(result, node, new ArrayList<String>()));
    

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

    0 讨论(0)
提交回复
热议问题