java 如何将 JSONObject 转换为 ArrayList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42726232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How convert JSONObject to ArrayList
提问by EunBin Lee
I'm trying to read a JSON, and store its value in dataVO. This dataVO includes ArrayList.
我正在尝试读取 JSON,并将其值存储在 dataVO 中。这个 dataVO 包括 ArrayList。
CODE:
代码:
if (jsonObject.get(fld.getName()) != null) {
if (fld.getType() == Integer.class) {
methList[i].invoke(mvo, Integer.parseInt(jsonObject.get(fldName).toString()));
} else if (fld.getType() == String.class) {
methList[i].invoke(mvo, jsonObject.get(fldName).toString());
} else if (fld.getType() == Long.class) {
methList[i].invoke(mvo, Long.valueOf(jsonObject.get(fldName).toString()));
} else if (fld.getType() == ArrayList.class) {
/* HERE!! */
}else {
methList[i].invoke(mvo, jsonObject.get(fldName).toString());
}
}
I do not know how to use methList[i].invoke in /* HERE!! */.
我不知道如何在 /* HERE 中使用 methList[i].invoke !!*/.
If I use
如果我使用
methList[i].invoke(mvo, jsonObject.get(fldName));
or
或者
methList[i].invoke(mvo, (ArrayList) jsonObject.get(fldName));
An error occured.
发生错误。
ERROR:
错误:
org.json.JSONObject cannot be cast to java.util.ArrayList
How can I fix this error?
我该如何解决这个错误?
回答by Shashwat Kumar
First use getJSONArray
to get JSONArray
from json object. Then explicit iteration is required to get ArrayList as no inbuilt function exists.
首先使用从 json 对象getJSONArray
获取JSONArray
。然后需要显式迭代来获取 ArrayList,因为不存在内置函数。
List<String> listdata = new ArrayList<>();
JSONArray jArray = jsonObject.getJSONArray(fldName);
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.getString(i));
}
}
methList[i].invoke(mvo, listdata);