How to decode a JSON Array on Android

Asked

Viewed 5,853 times

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();
    }
}

Imagem ilustrativa

  • Just use the method getJSONArray(int index), he will return what you want.

  • @Wakim Can show an example?

  • 1

    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.

  • 1

    @Wakim, puts! It’s vdd, I even forgot it kk; All right now, thanks (:

  • 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.

2 answers

4


To fetch a Array within a JSONArray is through the method getJSONArray.

Using your method:

private void _getCardapio(String result) {
    //...
    try {
        JSONArray json = new JSONArray(result);

        for (int i = 0; i < json.length(); i++) {
            //...

            // Agora voce possui um determinado array na posicao i
            JSONArray arrayDentroDoArray = json.getJSONArray(i);

            // Itera sobre cada objeto do array interno
            for(int j = 0; j < arrayDentroDoArray.length(); ++j) {
                JSONObject objeto = arrayDentroDoArray.getJSONObject(j);
                // Usar o objeto
            }

            //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();
    }
}

Watch out because if the position guy i is not a Array he will launch a JSONException. What you could do, if you’re not sure, is:

Object o = json.get(i);

if(o instanceof JSONArray) {
    // Trabalhar com o Array
} else if(o instanceof JSONObject) {
    // Trabalhar com o objeto
}
  • I’ll have to do another for pro arrayDentroDoArray. Right?

  • That will be 2 iterations, one for each JSONArray and another for each JSONObject within each JSONArray.

  • Don’t you think you’ll create one "gargalo" and slow down the app, or not? rs

  • You can linearize this JSON initial having only objects and not object lists. I believe it does not get "slow" if you are using AsyncTask or AsyncTaskLoader. If you’re doing it inside the MainThread will be slow yes... If you are not using a AsyncTask to decode this JSON, recommend you do.

  • As a suggestion, I leave these links: http://developer.android.com/reference/android/AsyncTask.html and http://www.vogella.com/tutorials/AndroidBackProcessing/article.html.

  • Perfect; Yes, I’m using the AsyncTask.

  • A doubt: Because he keeps repeating the same Objeto in Listview?

  • How’s your code? Can I post to your question (Adapter if you can)? Contents are correct?

  • Okay, Updated!

Show 4 more comments

1

I think these links will help you in your doubt!

http://www.devmedia.com.br/trabalhando-com-json-em-java-o-pacote-org-json/25480

https://stackoverflow.com/questions/1568762/accessing-members-of-items-in-a-jsonarray-with-java

https://stackoverflow.com/questions/18983185/how-to-create-correct-jsonarray-in-java-using-jsonobject

more would be something like:

 //string json: contém array com três elementos
    String json_str = "{\"elenco\":[\"Json Leigh\", \"Mary Stylesheet\",  \"David Markupovny\"]}";

    //instancia um novo JSONObject passando a string como entrada
    JSONObject my_obj = new JSONObject(json_str);

    //recupera o array "elenco"  
    JSONArray elenco = my_obj.getJSONArray("elenco");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.