EunBin Lee
EunBin Lee

Reputation: 33

How convert JSONObject to ArrayList

I'm trying to read a JSON, and store its value in dataVO. This dataVO includes 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!! */.

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$1 cannot be cast to java.util.ArrayList

How can I fix this error?

Upvotes: 3

Views: 23851

Answers (1)

Shashwat Kumar
Shashwat Kumar

Reputation: 5287

First use getJSONArray to get JSONArray from json object. Then explicit iteration is required to get ArrayList as no inbuilt function exists.

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

Upvotes: 5

Related Questions