How to send Android json object to API?

Asked

Viewed 126 times

1

I need to mount a json object to send some data to my api. Here’s how I’m doing.

public void btnCadastrar(View view) {

    final EditText edtNome = ((EditText) findViewById(R.id.edtNome));
    final EditText edtSobrenome = ((EditText) findViewById(R.id.edtSobrenome));
    EditText edtCelular = ((EditText) findViewById(R.id.edtCelular));
    EditText edtCep = ((EditText) findViewById(R.id.edtCep));
    EditText edtLogradouro = ((EditText) findViewById(R.id.edtLogradouro));
    EditText edtBairro = ((EditText) findViewById(R.id.edtBairro));
    EditText edtLocalidade = ((EditText) findViewById(R.id.edtCidade));
    EditText edtUF = ((EditText) findViewById(R.id.edtUF));

    final String nome = edtNome.getText().toString();
    String sobrenome = edtSobrenome.getText().toString();
    String celular = edtCelular.getText().toString();
    String cep = edtCep.getText().toString();
    String logradouro = edtLogradouro.getText().toString();
    String bairro = edtBairro.getText().toString();
    String cidade = edtLocalidade.getText().toString();
    String uf = edtUF.getText().toString();

    //String dados = nome+ " "+sobrenome+" "+celular+" "+cep+" "+logradouro+" "+bairro+" "+cidade+" "+uf;
    String[] dados = new String[{"nome":nome, "sobrenome":sobrenome}];

    String url = "http://reservacomdomanda.com/areaAdmin/api/area_admin/usuario.php?dados="+dados;

    StringRequest srUrl = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    })
    {
        protected Map<String, String > getParams(){
            Map<String, String> params = new HashMap<String, String>();

            params.put("nome", edtNome.getText().toString());
            params.put("sobrenome", edtSobrenome.getText().toString());

            return params;
        }
    };

}

How can I do that?

1 answer

2


JSONObject jsonObject = new JSONObject();
jsonObject.put("nome", edtNome.getText().toString());
jsonObject.toString(); //json

Tip: If it was on an object (e.g., Addressjava), you could easily use Gson(). toJson(Endereco.class)

Browser other questions tagged

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