skip to Main Content

My code:

try {
    JSONArray array = new JSONArray(response.body());
    List<JSONArray> arr = new ArrayList<>();
    for (int i = 0; i < array.length(); i++) {
        arr.add(array.getJSONArray(i));
    }
    Log.d("arr",arr.toString());
}catch (JSONException e) {
    throw new RuntimeException(e);
} 

This is my arr:

[["bdbd","hdhs","hdhd","1234567890","[[shhs, sbbs, married], [sjsn, snsn, unmarried]]"]]

I want to convert the last element inside my arr

"[[shhs, sbbs, married], [sjsn, snsn, unmarried]]"

to a multidimensional ArrayList (ArrayList<ArrayList<String>>). How do I do this?

2

Answers


  1. Chosen as BEST ANSWER

    After finding no other solution, I just iterated over the whole string and appended each element to the arraylist like this:

    String temp = arr.get(0).get(4).toString();
    String details = "";
    ArrayList<String> temp1 = new ArrayList<>();
    ArrayList<ArrayList<String>> final = new ArrayList<>();
    for(int i=2; i<temp.length()-1; i++){
        if(temp.charAt(i) != ',' && temp.charAt(i) != ' ' && temp.charAt(i) != '['){
            if(temp.charAt(i) != ']')
                details += temp.charAt(i);
            else{
                temp1.add(details);
                final.add(temp1);
                temp1 = new ArrayList<>();
                details = "";
            }
        }
        else{
            if(!details.equals("")) {
                temp1.add(details);
            }
            details = "";
        }
    }
    

  2. There is a one liner solution. Don’t use json.org library use Jackson Json library. In this case all you veed to do is

    ObjectMapper om = new ObjectMapper();
    List<Object> myList = om.readValue(response.body(), List.class);
    

    Also, there is a JsonUtil class that is a thin wrapper over ObjectMapper that allows you to do the same without instantiating ObjectMapper:

    List<Object> myList = JsonUtils.readObjectFromJsonString(response.body(), List.class);
    

    JsonUtils comes with MgntUtils OpenSource library written and maintained by me. You can get it as a Maven artifact or on Github (including javadoc and source code). Here is Javadoc for JsonUtils class

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search