There was a need to decode a JSON Array
like this:
output: [ [{ }, { }], [{ }, { }] ]
I was doing this in a way that decoded a Array
like this:
output: [{ }, { }, { }]
Code of how you were doing:
Method to convert 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 to 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 Json Array
? Exemplify.
ISSUE:
According to response from @ Wakim , another question arose:
Why is the object repeating in ListView
? I think it's logic error rs.
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();
}
}