Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

317
Visualizações
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 ?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda