[英]cannot cast JSONObject to JSONArray
I'm trying to convert the JSON data that i get back to an array so I can use the data in a listView. 我正在尝试将返回的JSON数据转换为数组,以便可以在listView中使用该数据。
I got the following code: 我得到以下代码:
JSONObject jsonobject;
jsonobject = JSONFunctions.getJSONfromURL("example/url");
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonobject;
if (jsonArray != null) {
//do something with it
}
Note: I don't have any experience with Java. 注意:我对Java没有任何经验。
The method getJSONfromURL returns the JSON of the given URL that works just fine but the error is in JSONArray jsonArray = (JSONArray)jsonobject;
方法getJSONfromURL返回给定URL的JSON,该JSON可以正常工作,但错误在JSONArray jsonArray = (JSONArray)jsonobject;
It gives the following error: cannot cast JSONObject to JSONArray I've also tried this: JSONArray jsonArray = (JSONObject)(JSONArray)jsonobject;
它给出以下错误:无法将JSONObject JSONArray jsonArray = (JSONObject)(JSONArray)jsonobject;
为JSONArray我也尝试过这样做: JSONArray jsonArray = (JSONObject)(JSONArray)jsonobject;
I can't figure out what i'm doing wrong. 我不知道我在做什么错。
So how can I cast my jsonobject to a normal array that I can use as data for my listView? 那么如何将jsonobject转换为可以用作listView数据的普通数组?
A JSONObject
is distinct from a JSONArray
. JSONObject
与JSONArray
。 If you try new JSONObject("['test', 'array']")
, you will get a JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
. 如果尝试使用new JSONObject("['test', 'array']")
,则将收到JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
。
Try whether this works for you: 尝试是否适合您:
static JSONArray fromUrl(URL url) throws IOException {
try (
InputStream openStream = url.openStream();
BufferedInputStream bis = new BufferedInputStream(openStream);
Scanner scanner = new Scanner(bis, StandardCharsets.UTF_8.name());
) {
if (!scanner.useDelimiter("\\A").hasNext()) {
throw new EOFException("empty response");
}
return new JSONArray(scanner.next());
}
}
JSONObject is like a Map in java. JSONObject就像Java中的Map。 Key-value pair. 键值对。 So, you should iterate like iterating a Map: 因此,您应该像迭代Map一样进行迭代:
Iterator iterator = jsonobject.keys();
JSONArray jsonArray = new JSONArray();
while (iterator.hasNext()){
String key = (String) iterator.next(); // assuming the key to be a String
// You can put the key also if you want. But, It does not make any sense to do so.
jsonArray.put(jsonobject.get(key));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.