使用 volley 中断来自服务器的 JSON 响应

break JSON response from server using volley

我正在使用 Volley 库将 POST 数据发送到服务器,并且我收到来自服务器的 JSON 响应,如下所示。

现在我可以轻松访问 "code"status

问题是我无法访问 "name""user" 的其他属性。 我尝试了以下问题,但它们对我没有帮助,也许那是因为我对 JSON 和 android.

很陌生

how to convert json object to string in android..?

How to convert json object into string in Android

JSONObject to String Android

How to convert this JSON object into a String array?

我正在使用 volley 库,这里是代码:

StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {

@Override
    public void onResponse(String response) {
    try {

JSONObject jsonResponse = new JSONObject(response);
String code = jsonResponse.getString("status");

} catch (JSONException e) {
     e.printStackTrace();
}

}
},
new Response.ErrorListener() {
 @Override
 public void onErrorResponse(VolleyError error) {
      error.printStackTrace();
      }
    }
     ) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> params = new HashMap<>();
                        // the POST parameters:
                        params.put("name", userName);
                        params.put("email", userEmail);
                        params.put("password",userPass);
                        params.put("deviceIdentifier", deviceIdent);
                        params.put("deviceType", deviceI);

                        return params;
                    }
                };
                Volley.newRequestQueue(context).add(postRequest);

您必须先获取 JSON 个对象:

JSONObject response = new JSONObject(responseString);
if (response.has("data") {
   JSONObject data = response.getJSONObject("data");
   if (data.has("user") {
      JSONObject user = data.getJSONObject("user");
      String name = user.optString("name", "");
   }
}

您的回复是这样构建的:

{ // JSONObject (lets call it response)
   "status": true, // boolean inside "response" JSONObject
   "code": 200, // int inside "response" JSONObject
   "data": { // JSONObject (lets call it data) inside "response" JSONObject
      [...], // Some more objects inside "data" JSONObject
      "user": { // JSONObject (lets call it user) inside "data" JSONObject
         [...], // Some more objects inside "user" JSONObject
         "name": "abc", // String inside "user" JSONObject
         [...], // Some more objects inside "user" JSONObject
      }
   }
}