如何从JSONArray获取JSONObject?

问题描述 投票:1回答:2

我尝试从json数组获取json对象时遇到问题。捕获的错误表明JSONArray无法转换为JSONObject。有效地可以从Web服务获取JSON响应,但我不知道如何将数组转换为对象

错误消息

org.json.JSONException: Value [{"codaspirante":"1","nombre":"Saul","apellido":"Goodman","mail":"[email protected]","telefono":"012034948123","codusuario":"0"},{"codaspirante":"2","nombre":"Lalo","apellido":"Salamanca","mail":"[email protected]","telefono":"12351233","codusuario":"10"},{"codaspirante":"3","nombre":"Walter","apellido":"White","mail":"[email protected]","telefono":"54843439","codusuario":"10"},{"codaspirante":"4","nombre":"Gustavo","apellido":"Frings","mail":"[email protected]","telefono":"845738848434","codusuario":"10"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject

方法:

 private void buscarCandidatos_Serivicio(String URL){
  JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, URL, null, new Response.Listener<JSONArray>() {
      @Override
      public void onResponse(JSONArray response) {
          try {
              for (int i = 0; i < response.length(); i++) {
                  JSONObject candidato = response.getJSONObject(i);

                  Candidato c = new Candidato(
                          candidato.getInt("codaspirante"),
                          candidato.getString("nombre"),
                          candidato.getString("apellido"),
                          candidato.getString("mail"),
                          candidato.getString("telefono"),
                          candidato.getInt("codusuario")
                          );
                  listaCandidatos.add(c);
              }

          } catch (JSONException e) {
              Toast.makeText(getApplicationContext(), e.getMessage().toString(), Toast.LENGTH_SHORT).show();
          }
      }
  }, new Response.ErrorListener() {
      @Override
      public void onErrorResponse(VolleyError error) {
          Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
      }
  }
  );

    RequestQueue rq= Volley.newRequestQueue(this);
    rq.add(jsonArrayRequest);
}
android-studio android-volley
2个回答
1
投票

错误是因为response.getJSONObject(0)返回JSONArray而不是JSONObject。

我猜您想从该数组中获取数据。在On响应方法中,应添加response = response.getJSONArray(0)。

    public void onResponse(JSONArray response) {
      try {
          response = response.getJSONArray(0);
          for (int i = 0; i < response.length(); i++) {        

应该可以解决您的问题。


0
投票
  val stringRequest = object : StringRequest(
            Request.Method.POST, Config."your URL",
            Response.Listener<String> { response ->
                try {

                    val obj = JSONObject(response)

                    if (!obj.getBoolean("error")) {

                        val userssListArray = obj.getJSONArray("arrayname")

                        for (i in 0 until userssListArray.length()) {
                            var usersObj = userssListArray.getJSONObject(i)

                        }


                    } else {

                        if (obj.getString("message") == "Your login expired please re login") {
                            val intent = Intent(this, LoginActivity::class.java)
                            startActivity(intent)
                            finish()
                        }
                    }
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            },
            Response.ErrorListener {
                Toast.makeText(this, "Network Error Try Again...", Toast.LENGTH_LONG).show()

            }) {
        @Throws(AuthFailureError::class)
        override fun getParams(): Map<String, String> {
            val params = HashMap<String, String>()

            return params
        }
    }
    stringRequest.retryPolicy = DefaultRetryPolicy(
            15000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
    //adding request to queue
    VolleySingleton.instance?.addToRequestQueue(stringRequest)

您可以像这样使用排球

© www.soinside.com 2019 - 2024. All rights reserved.