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

257
Visualizações
Parse JSON with dynamic key object inside dynamic key object with Gson

I am a newbie to android and I have a JSON file with dynamic key like this:

{
  "x": {
    "a": {
      "1": [1,2,3,4],
      "2": [1,2,3,4]
    },
    "b": {
      "1": [1,2,3,4],
      "2": [1,2,3,4]
    }
  },
  "y": {
    "a": {
      "1": [1,2,3,4],
      "2": [1,2,3,4]
    },
    "b": {
      "1": [1,2,3,4],
      "2": [1,2,3,4]
    }
  },
  "z": {
    "a": {
      "1": [1,2,3,4],
      "2": [1,2,3,4]
    },
    "b": {
      "1": [1,2,3,4],
      "2": [1,2,3,4]
    }
  }
}

I parsed it successfully by JSONObject but I have to loop by keys Iterator on x, y, z. For each time, I have to loop on a, b and the same for "1" and "2". I think it's not a good solution. I created models for them like this:

Class XYZ {
private String name; // "x", "y", "z" value
private ArrayList<ABC> abcList;
}

Class ABC {
private String name; // "a", "b", "c"
private ArrayList<Item> itemList;
}

Class Item{
private String ID; // "1", "2"
private int[] valueArray;
}

Can anyone help me to parse this json by Gson, I think it looks more professional :D. Thank you so much

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

0

Your models cannot map your JSON just because Gson default configuration clearly gets them unmatched.

You can have two "default" ways:

static

... since you didn't really mention why your JSON is considered dynamic:

final class XYZ {

    final ABC x = null;
    final ABC y = null;
    final ABC z = null;

}
final class ABC {

    final OneTwo a = null;
    final OneTwo b = null;

}
final class OneTwo {

    @SerializedName("1")
    final List<Integer> one = null;

    @SerializedName("2")
    final List<Integer> two = null;

}

Example:

try ( final Reader reader = getPackageResourceReader(Q43695739.class, "dynamic.json") ) {
    final XYZ xyz = gson.fromJson(reader, XYZ.class);
    System.out.println(xyz.x.b.two);
}

dynamic (by deserialization)

... assuming your keys are dynamic, but the structure remains the same:

private static final Type stringToStringToStringToIntegerListType = new TypeToken<Map<String, Map<String, Map<String, List<Integer>>>>>() {
}.getType();
try ( final Reader reader = getPackageResourceReader(Q43695739.class, "dynamic.json") ) {
    final Map<String, Map<String, Map<String, List<Integer>>>> m = gson.fromJson(reader, stringToStringToStringToIntegerListType);
    System.out.println(m.get("x").get("b").get("2"));
}

dynamic (by JSON trees)

Another true dynamic approach that may be helpful for some scenarios. Also note that JSONObject is not in the Gson realm: you probably might have imported this one from the org.json package. Gson uses camel-cased names like JsonElement, JsonObject, etc.

try ( final Reader reader = getPackageResourceReader(Q43695739.class, "dynamic.json") ) {
    final JsonElement jsonElement = gson.fromJson(reader, JsonElement.class)
            .getAsJsonObject()
            .getAsJsonObject("x")
            .getAsJsonObject("b")
            .getAsJsonArray("2");
    System.out.println(jsonElement);
}

The first and the second examples produce java.util.List instances

[1, 2, 3, 4]

The third example returns a JsonArray instance with a slightly different toString implementation:

[1,2,3,4]

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