obtener nombres clave del objeto JSON usando Gson
Tengo un objeto JSON del que me gustaría obtener los nombres clave y almacenarlos en una ArrayList. He usado el siguiente código
jsonData(String filename) {
JsonParser parser = new JsonParser();
JsonElement jsonElement = null;
try {
jsonElement = parser.parse(new FileReader(filename));
} catch (JsonIOException | JsonSyntaxException | FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonObject jsonObject = jsonElement.getAsJsonObject();
int i = 0;
for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
String key = entry.getKey();
JsonElement value = entry.getValue();
keys.add(key);
i++;
}
nKeys = i;
}
Si utilizo este código con un simple objeto JSON
{
"age":100,
"name":"mkyong.com",
"messages":["msg 1","msg 2","msg 3"]
}
Esto funciona bien. la edad, el nombre y los mensajes (no los valores) se agregan a mi ArrayList. Una vez que intento y uso este mismo código con un JSON más complejo como este
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
Solo obtengo la clave de root. ¿Puede alguien apuntarme en la dirección correcta con esto?
¡Gracias a todos!