如何将JSONObject转换为ArrayList

3

我想要读取一个JSON,并将其值存储在dataVO中。该dataVO包含ArrayList。

代码:

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());
     }
}

我不知道如何在/*此处!!*/使用methList[i].invoke。
如果我使用

标签,则会在此处结束段落,这可能会导致语法错误。
methList[i].invoke(mvo, jsonObject.get(fldName));

或者

methList[i].invoke(mvo, (ArrayList) jsonObject.get(fldName));

发生了错误。
错误信息:
org.json.JSONObject$1 cannot be cast to java.util.ArrayList

我该如何修复这个错误?
1个回答

5
首先使用getJSONArray从json对象中获取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);

我尝试了你的代码,但是出现了以下错误:org.json.JSONException: Value null at option_list of type org.json.JSONObject$1 cannot be converted to JSONArray。 - EunBin Lee
可能已经解决了问题(org.json.JSONException)。但是,当我使用get函数调用Activity时,出现错误:java.lang.ClassCastException: java.lang.String无法转换为com.top_adv.myapplication1.DataVO.Ref_listVO。 - EunBin Lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接