-3

I need to send something like:

{
 "username": "username",
 "password": "password",
 "email": "email@email.com",
 "usuario": {
    "municipio": 1,
    "estado": 1
  }
}

How can I do that? If I try with this code it doesn't work:

StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(getApplicationContext(), R.string.AlertaExito, Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("username", txtusuario.getText().toString());
                params.put("password", txtpassword.getText().toString());
                params.put("email", txtemail.getText().toString());
                params.put("estado", txtestado.getText().toString());
                params.put("municipio", txtmunicipio.getText().toString());

                return params;
            }

I think I should create a jsonobject but I don't know how to do that.

alistaire
  • 42,459
  • 4
  • 77
  • 117
PoYo Rivera
  • 153
  • 1
  • 2
  • 10

1 Answers1

0

If your problem is with volley itself you can check its tutorial https://developer.android.com/training/volley/request.html#request-json (use the singleton from the previous lesson https://developer.android.com/training/volley/requestqueue.html#singleton).

There they are making a GET request but you can change for a POST with Request.Method.POST, the signature for the JsonObjectRequest is JsonObjectRequest(int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener) found here https://android.googlesource.com/platform/frameworks/volley/+/1b4858087f25a8033c5136a96b750752b87e128c/src/com/android/volley/toolbox/JsonObjectRequest.java

If your problem is with your json, then just notice that JsonObjectRequest needs a JSONObject, so you can't just send a String, you can check the JSONObject documentation (https://developer.android.com/reference/org/json/JSONObject.html) and recreate the json through its methods or it also has one constructor which uses a String json encoded.

Edwin
  • 836
  • 7
  • 17