json在kotlin应用程序中的异常

我正在尝试读取kotlin应用程序中的JSON文件。 我可以阅读JSON,但有一个错误,它不填充数组。 当它显示异常时,我可以看到json结果。 这里是代码:

fun read(){ val stringRequest = StringRequest(Request.Method.POST, URL, Response.Listener<String>{s -> try { val obj = JSONObject(s) if(!obj.getBoolean("error")){ val array = obj.getJSONArray("friend") for(i in 0..array.length()-1){ val objectFriend = array.getJSONObject(i) val friend = Friend(objectFriend.getString("name"), objectFriend.getString("surname")) listaPersonas.add(friend) } } }catch (e: JSONException){ e.printStackTrace() } },Response.ErrorListener { error: VolleyError? -> Log.e("error", "error") }) val requesQueue = Volley.newRequestQueue(this) requesQueue.add<String>(stringRequest) } 

这是例外:

 org.json.JSONException: Value [value of json] of type org.json.JSONArray cannot be converted to JSONObject 09-30 22:25:06.241 17310-17310/com.example.user.kotlinjson W/System.err: at org.json.JSON.typeMismatch(JSON.java:111) 09-30 22:25:06.242 17310-17310/com.example.user.kotlinjson W/System.err: at org.json.JSONObject.<init>(JSONObject.java:160) 09-30 22:25:06.242 17310-17310/com.example.user.kotlinjson W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173) 09-30 22:25:06.242 17310-17310/com.example.user.kotlinjson W/System.err: at com.example.smoreno.kotlinprueba.MainActivity$read$stringRequest$1.onResponse(MainActivity.kt:139) 09-30 22:25:06.242 17310-17310/com.example.smoreno.kotlinprueba W/System.err: at com.example.smoreno.kotlinprueba.MainActivity$read$stringRequest$1.onResponse(MainActivity.kt:22) 09-30 22:25:06.242 17310-17310/com.example.smoreno.kotlinprueba W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60) 09-30 22:25:06.242 17310-17310/com.example.smoreno.kotlinprueba W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30) 

有可能你得到JsonArray作为空值或空值的响应,你试图转换为JsonObject。 尝试下面给出的代码。

更换

 val obj = JSONObject(s) 

 if(s != null && s.isNotEmpty()) { val obj = JSONArray(s) // rest of code here }