Escolar Documentos
Profissional Documentos
Cultura Documentos
ANDROID
JSON
{“planetas”:
[
{ “nome”: “Mercurio”,
“posicao”:1, Planetas é um array de objetos
“habitavel”:false
},
{ “nome”: “Terra”,
“posicao”:3,
“habitavel”:true
}
]
}
JSON
• Para aprender a manipular (na terminologia de
desenvolvimento chama-se fazer parser) o JSON vamos
criar uma classe que exibe os dados no JSON no LogCat
try {
JSONObject planetas = new JSONObject(jsonPlanetas);
JSONArray arrayPlanetas = planetas.getJSONArray("planetas");
for (int i= 0; i < arrayPlanetas.length();i++) {
JSONObject planeta = arrayPlanetas.getJSONObject(i);
Log.d("MainActivity",planeta.getString("nome"));
Log.d("MainActivity", Integer.toString(planeta.getInt("posicao")));
Log.d("MainActivity", Boolean.toString(planeta.getBoolean("habitavel")));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
JSON
• Vejamos o resultado no arquivo de Log
JSON
• Vamos analisar as linhas de código:
{“planetas”:
[
{ “nome”: “Mercurio”,
“posicao”:1,
“habitavel”:false
},
{ “nome”: “Terra”,
“posicao”:3,
“habitavel”:true
}
]
}
JSON
// obtém o array contendo todos os planetas
JSONArray arrayPlanetas = planetas.getJSONArray("planetas");
{“planetas”:
[
{ “nome”: “Mercurio”,
“posicao”:1,
“habitavel”:false
},
{ “nome”: “Terra”,
“posicao”:3,
“habitavel”:true
}
]
}
JSON
// percorrer todos os planetas
for (int i= 0; i < arrayPlanetas.length();i++) {
// obtém o objeto planeta
JSONObject planeta = arrayPlanetas.getJSONObject(i);
{“planetas”:
[
{ “nome”: “Mercurio”,
“posicao”:1,
“habitavel”:false
},
{ “nome”: “Terra”,
“posicao”:3,
“habitavel”:true
}
]
}