Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic multi level hierarchy JSON to Java Pojo. Re-use for multiple projects

I have JSON like below

{
    "name" : "sahal",
    "address" : [
        {
           "state" : "FL"
        },
        {
           "country" : "FL",
           "city" : {
               "type" : "municipality",
               "value" : "California City"
           }
        },
        {
           "pin" : "87876"
        }
    ]
}

None of the key:value is constant. Name can change any time. And some time name comes like FirstName.

I tried with @JsonAnySetter and @JsonNode. These works with only one hierarchy

Any other way I can do this and reuse it for other JSON structure without writing the Pojo for each projects ?

like image 582
Sahal Avatar asked Nov 21 '25 12:11

Sahal


1 Answers

Consider to use JsonNode and fuse a hierarchy loop to extract all the keys and values dynamically regardless of patterns and relations and values,

    public static void main(String[] args) throws JsonProcessingException {
        //which hierarchy is your json object
        JsonNode node = nodeGenerator(hierarchy);
        JSONObject flat = new JSONObject();
        node.fields().forEachRemaining(o -> {
            if (!o.getValue().isContainerNode())
                flat.put(o.getKey(), o.getValue());
            else {
                parser(o.getValue(), flat);
            }
        });
        System.out.println(flat);
        System.out.println(flat.get("type"));
    }

    public static JsonNode nodeGenerator(JSONObject input) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readTree(input.toString());
    }

    public static void parser(JsonNode node, JSONObject flat) {
        if (node.isArray()) {
            ArrayNode array = node.deepCopy();
            array.forEach(u ->
                    u.fields().forEachRemaining(o -> {
                        if (!o.getValue().isContainerNode())
                            flat.put(o.getKey(), o.getValue());
                        else {
                            parser(o.getValue(), flat);
                        }
                    }));
        } else {
            node.fields().forEachRemaining(o -> flat.put(o.getKey(), o.getValue()));
        }
    }

Which in your case extracted json will be as follow : enter image description here

like image 186
Lunatic Avatar answered Nov 23 '25 03:11

Lunatic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!