How to receive a data from a JSONObject to a simple array

Lucca Germano :

I am trying to get a int that is inside a JSONObject and put it in a String Array, but i only can put it in a simple String.

This is what inside the JSONObject {"codigo":2,"nome":"Teste 2"}

That is the code that i can pass the int from codigo to a simple String

String informacao;
    String code;
    String name[];

    ListView listView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        informacao = intent.getStringExtra("INFO");

        try{
            JSONObject jo = new JSONObject(informacao);

            for (int i = 0; i < jo.length(); i++){
                Log.i("ENTROU", "entrou");
                code = jo.getString("codigo").toString();
                Log.i("CODE!!!", code.toString());
            }
        } catch (JSONException e){
            Log.i("ERRO", e.toString());
        }

Logcat from it

2020-03-20 09:48:48.046 23998-23998/br.com.ifractal.Stou I/ENTROU: entrou
2020-03-20 09:48:48.046 23998-23998/br.com.ifractal.Stou I/CODE!!!: 2
2020-03-20 09:48:48.046 23998-23998/br.com.ifractal.Stou I/ENTROU: entrou
2020-03-20 09:48:48.046 23998-23998/br.com.ifractal.Stou I/CODE!!!: 2

Now when i try to put it in a String Array

String informacao;
    String code[];
    String name[];

    ListView listView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        informacao = intent.getStringExtra("INFO");

        try{
            JSONObject jo = new JSONObject(informacao);

            for (int i = 0; i < jo.length(); i++){
                Log.i("ENTROU", "entrou");
                code[i] = jo.getString("codigo").toString();
                Log.i("CODE!!!", code[i].toString());
            }
        } catch (JSONException e){
            Log.i("ERRO", e.toString());
        }

Logcat from that

2020-03-20 09:56:25.195 25695-25695/br.com.ifractal.Stou I/ENTROU: entrou
InsertKnowledge :

You are not setting the length of the array. It doesn't dynamically increase like in JavaScript. If you initialize the array like so: String code[] = new String[10]; you should be able to set its elements.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=334169&siteId=1