2016-05-31 62 views
-3

我需要發送類似發送的JSONObject:如何與Android凌空

{ 
"username": "username", 
"password": "password", 
"email": "[email protected]", 
"usuario": { 
    "municipio": 1, 
    "estado": 1 
    } 
} 

我怎麼能這樣做?如果我嘗試使用此代碼它不工作:

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; 
      } 

我想我應該創建一個jsonobject,但我不知道該怎麼做。

回答

0

如果您的問題與排球本身有關,您可以查看其教程https://developer.android.com/training/volley/request.html#request-json(使用上一課https://developer.android.com/training/volley/requestqueue.html#singleton中的單例)。

在那裏,他們正在一個GET請求,但您可以爲POST與Request.Method.POST改變,對於JsonObjectRequest簽名是JsonObjectRequest(int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener)這裏https://android.googlesource.com/platform/frameworks/volley/+/1b4858087f25a8033c5136a96b750752b87e128c/src/com/android/volley/toolbox/JsonObjectRequest.java

如果你的問題是在你的JSON發現,然後就發現JsonObjectRequest需要JSONObject,所以你不能只發送一個字符串,你可以檢查JSONObject文檔(https://developer.android.com/reference/org/json/JSONObject.html)並通過它的方法重新創建json,或者它也有一個使用String json編碼的構造函數。

+0

我不知道如何創建我的json對象以便在getParams()方法中提交它 –