Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created February 11, 2019 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/124117da78ca9c3bd33f12d29f8a02f6 to your computer and use it in GitHub Desktop.
Save parzibyte/124117da78ca9c3bd33f12d29f8a02f6 to your computer and use it in GitHub Desktop.
String cadenaJson = "[{\"nombre\":\"Maggie\",\"edad\":3},{\"nombre\":\"Snowball\",\"edad\":1},{\"nombre\":\"Bichi\",\"edad\":1},{\"nombre\":\"Meca\",\"edad\":5}]";
JSONArray arregloJson = new JSONArray(cadenaJson);
// Nota: creamos la lista para ejemplos ilustrativos, no es necesaria
ArrayList<Mascota> mascotas = new ArrayList<>();
// Iterar
for (int indice = 0; indice < arregloJson.length(); indice++) {
// Obtener objeto a través del índice
JSONObject posibleMascota = arregloJson.getJSONObject(indice);
// Acceder como accedíamos al jsonObject
int edad = posibleMascota.getInt("edad");
String nombre = posibleMascota.getString("nombre");
// Luego de eso podemos crear la clase y obtener los beneficios
// de la POO o usar los datos como nos plazca
Mascota mascota = new Mascota(nombre, edad);
// Podemos hacer lo que sea con el objeto
mascota.ladrar();
// Agregar a la lista, solo para ilustrar
mascotas.add(mascota);
}
// Aquí hacer lo que sea con la lista de mascotas
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment