3
The need to decode a JSON Array
thus:
output: [ [{ }, { }], [{ }, { }] ]
I was doing it in a way that decoded a Array
that way:
output: [{ }, { }, { }]
Code of how I was doing:
Method to convert to Entity
private CardapioEntities convertCardapio(JSONObject obj) throws JSONException {
String titulo = obj.getString(TAG_TITULO);
String descricao = obj.getString(TAG_DESCRICAO);
String preco = obj.getString(TAG_PRECO);
String tipo = obj.getString(TAG_TIPO);
return new CardapioEntities(titulo, descricao, preco, tipo);
}
Method to add Listview
private void _getCardapio(String result) {
//...
try {
JSONArray json = new JSONArray(result);
for (int i = 0; i < json.length(); i++) {
//...
cardapioEntities.setCardapioPreco(convertCardapio(json.getJSONObject(i)).getCardapioPreco());
listaLanches.add(cardapioEntities);
}
//...
final ListView lvLanches = (ListView) findViewById(R.id.lvLanches);
lvLanches.setAdapter(new CustomListAdapter(this, listaLanches));
//...
} catch (JSONException e) {
e.printStackTrace();
}
}
Question:
How to adapt this code to read the Json Array
? Exemplify.
EDITION:
In accordance with the reply of @Wakim, another question arose:
Why is the object repeating in the ListView
? I think it’s Logic’s mistake.
private void _getCardapio(String result) {
//...
try {
JSONArray json = new JSONArray(result);
for (int i = 0; i < json.length(); i++) {
CardapioEntities cardapioEntities = new CardapioEntities();
JSONArray arrayDentroDoArray = json.getJSONArray(i);
for (int j = 0; j < arrayDentroDoArray.length(); j++) {
JSONObject objeto = arrayDentroDoArray.getJSONObject(j);
if (convertCardapio(objeto).getCardapioTipo() == 0) {
cardapioEntities.setCardapioTitulo(convertCardapio(objeto).getCardapioTitulo());
cardapioEntities.setCardapioDescricao(convertCardapio(objeto).getCardapioDescricao());
cardapioEntities.setCardapioPreco(convertCardapio(objeto).getCardapioPreco());
listaLanches.add(cardapioEntities);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Just use the method
getJSONArray(int index)
, he will return what you want.– Wakim
@Wakim Can show an example?
– Leonardo
The error is where is instantiating the
CardapioEntities
, create the instance within the innermost iteration. For it is always modifying the same instance within the iteration, and the last change is that it prevails.– Wakim
@Wakim, puts! It’s vdd, I even forgot it kk; All right now, thanks (:
– Leonardo
Why don’t you use the lib GSON to do this ? , with the lib you will leave in charge of the GSON do all the work your code will be much simpler, cleaner and more protected.
– Duanniston Cardoso Cabral