当我在 android studio 中使用 volley 时,如何获得响应并遍历 Json?如果是多维数组

When i'm using volley in android studio how to get response and iterate over Json ? if it is multi-dimensional array

我不能使用 JsonObjectRequest 而不是 StringRequest,因为我需要通过 POST 方法发送它

在分析了很多解决方案后,我把问题贴在这里

我的phpapi输出看起来像

[
  {
    "username": "arun",
    "password": "kumar"
  },
  {
    "username": "arun",
    "password": "ak"
  },
  {
    "username": "arun",
    "password": "mypass"
  },
  {
    "username": "arun",
    "password": "TestPW"
  }
]

在Android这边,我使用下面的代码从网络中获取数据,在方法中 public无效onresponse() 我不知道如何获得上述 json 响应,也不知道如何遍历响应以打印响应

中的所有数据
String url = "http://myipaddress/index.php";

StringRequest request = new StringRequest(Request.Method.POST, url, new response.Listener<String>() {
  @Override
  public void onResponse(String response) {
    try {
      JSONObject jsonobject = new JSONObject(response);
      String output = "";
      for (int i = 0; i < jsonobject.length(); i++) {
        // print all usernames and passwords
      }

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

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

  }
}) {
  @Override
  protected Map<String, String> getParams() throws AuthFailureError {
    Map<String, String> params = new HashMap<>();
    params.put("username", username);
    return params;
  }
};

RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);

您需要遍历 JSONArray 并将每个元素作为 JSONObject,然后从中获取名为 "username""password"String 属性他们每个人。

试试这个:

    String url = "http://myipaddress/index.php";

    StringRequest request = new StringRequest(Request.Method.POST, url, new response.Listener<String>() {
      @Override
      public void onResponse(String response) {
        try {
          JSONArray array = new JSONArray(response);
          for (int i = 0; i < array.length(); i++) {
            JSONObject object = array.getJSONObject(i);
            final String username = object.getString("username");
            final String password = object.getString("password");
            // print the output
            Log.d("TAG", "username=" + username + ", password=" + password);
          }
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }
    }, new Response.ErrorListener() {
      @Override
      public void onErrorResponse(VolleyError error) {

      }
    }) {
      @Override
      protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> params = new HashMap<>();
        params.put("username", username);
        return params;
      }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(request);

理想情况下,您应该改用 class 模型,并直接反序列化到此 class。

public class UserLoginInfo {
  public String username;
  public String password;
}

这将使对象更易于使用,并为您提供类型安全和自动完成的好处。

This is a link 来自关于如何使用 Google 的 gson 库的简短 google 搜索。

IMO use retrofit.

编码愉快! :)