【问题标题】:How get an JSONObject from a JSONArray?如何从 JSONArray 中获取 JSONObject?
【发布时间】:2020-05-12 16:54:19
【问题描述】:

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

错误信息

org.json.JSONException: Value [{"codaspirante":"1","nombre":"Saul","apellido":"Goodman","mail":"sg@g.com","telefono":"012034948123","codusuario":"0"},{"codaspirante":"2","nombre":"Lalo","apellido":"Salamanca","mail":"ls@g.com","telefono":"12351233","codusuario":"10"},{"codaspirante":"3","nombre":"Walter","apellido":"White","mail":"ww@g.com","telefono":"54843439","codusuario":"10"},{"codaspirante":"4","nombre":"Gustavo","apellido":"Frings","mail":"gf@g.com","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);
}

【问题讨论】:

  • 您的响应以数组形式出现,但您正在将其转换为 jsonobject

标签: android-studio android-volley


【解决方案1】:

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

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

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

这应该可以解决您的问题。

【讨论】:

    【解决方案2】:
      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)
    

    你可以像这样使用截击

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      相关资源
      最近更新 更多