这是给我带来问题的函数:
public String URLToJson() {
String result = "";
String jsonString = ReadingURL(" here goes my URL that reads a JSON ");
JSONObject jsonResult = null;
try {
jsonResult = new JSONObject(jsonString);
JSONArray data = jsonResult.getJSONArray("Configuracion");
if (data != null) {
for (int i = 0; i <= data.length(); i++) {
result = result + "Dirección: " + data.getJSONObject(i).getString("Direccion") + "\n";
result = result + "Cédula: " + data.getJSONObject(i).getString("Cedula") + "\n";
result = result + "Nombre: : " + data.getJSONObject(i).getString("Nombre") + "\n";
result = result + "Teléfono : " + data.getJSONObject(i).getString("Telefono") + "\n";
result = result + "Hacienda: " + data.getJSONObject(i).getString("Hacienda") + "\n";
}
}
return result;
}catch (JSONException e){
e.printStackTrace();
return "Error Reading JSON Data";
}
}
然后出现了:
`W/System.err: org.json.JSONException: Value {"Direccion":"Somewhere","Cedula":"111111","Nombre":"Something","Telefono":"2222-2440","Hacienda":"Something"} at Configuracion of type org.json.JSONObject cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java:100)
W/System.err: at org.json.JSONObject.getJSONArray(JSONObject.java:588)
at com.example.user.mypos.PrintManager.URLToJson(PrintManager.java:977)
W/System.err: at com.example.user.mypos.PrintManager$4.run(PrintManager.java:917)
at java.lang.Thread.run(Thread.java:818)W/System.err: org.json.JSONException: Value { the values that are supposed to be } of type org.json.JSONObject cannot be converted to JSONArray`
ReadingURL 基本上读取 URL 的内容,该 URL 在 String 中具有 JSON。
最佳答案
从异常中可以清楚地看出,URL 返回的 JSON 字符串属于 JSONObject 类型,而不是 JSONArray。
Value { the values that are supposed to be } of type org.json.JSONObject cannot be converted to JSONArray
JSON 对象将以 { 开始并以 } 结束
{ "KEY1":"VALUE1", "KEY2":"VALUE2" }
JSON 数组将以 [ 开始并以 ] 结束。
[
{"KEY1":"VALUE1","KEY2":"VALUE2"},{"KEY1":"VALUE1","KEY2":"VALUE2"}
]
所以你得到这个异常是因为你试图将 JSON 对象转换为 JSON 数组。
关于java - 值无法转换为 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53012986/