How to read Json with Android

Asked

Viewed 1,120 times

1

I wonder how I read json in two different ways.

1 - I have a Json

{"nome": "JOA", "cpf": 7.4417, "idade": "15"},{"nome": "PAT", "cpf": 8.5528, "idade": "20"}"};

This one I can read and play in variables, but only the first part, I would like to know how to get the value of the second part of json.

Follow the java code:

JSONObject obj;
String nome = "", cpf = "", idade = "";
String teste = "{\"nome\": \"JOA\", \"cpf\": 7.4417, \"idade\": \"15\"},{\"nome\": \"PAT\", \"cpf\": 8.5528, \"idade\": \"20\"}";
try {
    obj = new JSONObject(teste);
    nome = obj.getString("nome");
    cpf = obj.getString("cpf");
    idade = obj.getString("idade");

    //Toast.makeText(getApplicationContext(), nome, Toast.LENGTH_LONG).show();
}
catch (JSONException ex)
{

}

2 answers

2


This JSON is wrong:

{\"nome\": \"JOA\", \"cpf\": 7.4417, \"idade\": \"15\"},{\"nome\": \"PAT\", \"cpf\": 8.5528, \"idade\": \"20\"};

This format is broken and will not be read, you probably want something like:

[{\"nome\": \"JOA\", \"cpf\": 7.4417, \"idade\": \"15\"},{\"nome\": \"PAT\", \"cpf\": 8.5528, \"idade\": \"20\"}]

With [item1, item2], then how have I ever responded in:

Use JSONArray to pick arrays [] and JSONObject to pick up "objects" {...}, just iterate like this:

JSONObject obj;

String teste = "[{\"nome\": \"JOA\", \"cpf\": 7.4417, \"idade\": \"15\"},{\"nome\": \"PAT\", \"cpf\": 8.5528, \"idade\": \"20\"}]";

//Faz o parse
JSONArray minhaArray = new JSONArray(teste);

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

    //Pega o item atual
    obj = new JSONObject(minhaArray.getString(i));

    obj.getString("nome");
    obj.getString("cpf");
    obj.getString("idade");
}

If you want to take part "2", as the array starts to iterate from scratch then use the 1, thus: .getString(1):

String teste = "[{\"nome\": \"JOA\", \"cpf\": 7.4417, \"idade\": \"15\"},{\"nome\": \"PAT\", \"cpf\": 8.5528, \"idade\": \"20\"}]";

//Faz o parse
JSONArray minhaArray = new JSONArray(teste);

//Pega o item atual
JSONObject obj = new JSONObject(minhaArray.getString(1)); // Pega o item 2

nome = obj.getString("nome");
cpf = obj.getString("cpf");
idade = obj.getString("idade");
  • 1

    Here’s my +1; =D

  • 1

    Perfect, I understand now the concept of Arrey and Objects within Json.

  • @Did Patrickcamargo solve your problem? If yes, please mark the answer as correct, if you do not know how to do it read: https://pt.meta.stackoverflow.com/q/1078/3635

0

You can also read a JSON using GSON (a library that converts Java objects to JSON and vice versa)

Example of use:

public class ApiCliente {

    private Cliente cliente;

    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

    class Cliente {

        private int id;
        private String nome;
        private String RG;
        private String email;

        public Cliente() {
        }

        public Cliente(int id, String nome, String RG, String email) {
            this.id = id;
            this.nome = nome;
            this.RG = RG;
            this.email = email;
        }

        public int getId() { return id; }
        public void setId(int id) { this.id = id; }

        public String getNome() { return nome; }
        public void setNome(String nome) { this.nome = nome; }

        public String getRG() { return RG; }
        public void setRG(String RG) { this.RG = RG; }

        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }

        @Override
        public String toString() {
            return "Cliente{" +
                    "id=" + id +
                    ", nome='" + nome + '\'' +
                    ", RG='" + RG + '\'' +
                    ", email='" + email + '\'' +
                    '}';
        }
    }//fecha classe
}//fecha classe

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //JSON ESTÁTICO - JAVA
        String jsonCliente = "{cliente:{\"id\":\"1\",\"nome\":\"maria\",\"RG\":\"132456\",\"email\":\"[email protected]\"}}";

        Gson gson = new Gson();
        ApiCliente cli = gson.fromJson(jsonCliente,ApiCliente.class);

        Toast.makeText(
                getBaseContext(),
                "OBJETO EM JAVA: "+cli.getCliente().toString(),
                Toast.LENGTH_LONG).show();

    }//fecha oncreate
}//fecha classe

GSON needs to import Compile:

compile 'com.google.code.gson:gson:2.8.1'

Browser other questions tagged

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