How to send json object from Android to API?

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 this?

    
asked by anonymous 25.08.2017 / 14:51

1 answer

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

Tip: If you were in an object (eg, Address.java), you could easily use Gson (). toJson (Endereco.class)

    
25.08.2017 / 15:28