Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse JSON string into ArrayList using Java?

Tags:

java

I am getting following response from an API

String response={"balance":1000,
  "lastliability":2000,"profitarray":[[1,2,3],[67,88,99]],"previous":[99,88]}

I am trying to convert profitarray to ArrayList in Java like

    JSONObject res=new JSONObject(response);
    ArrayList<ArrayList<Integer>> temp=res.getString("profitarray")//something like this
ArrayList<Integer>yy=res.getString("previous");

Obviously, the outputs of res.getstring will be String and I want to convert them to ArrayList, any idea how to do it?


1 Answers

Could be a complex way to do it, but since you wanted an ArrayList>, here we are

public static void main(String[] args) {
    String response = "{\"balance\":1000,\n" +
            "  \"lastliability\":2000,\"profitarray\":[[1,2,3],[67,88,99]],\"previous\":[99,88]}";
    JSONObject res=new JSONObject(response);
    JSONArray array = res.getJSONArray("profitarray");
    ArrayList<JSONArray> profitList = new ArrayList<>();
    for (int i = 0; i < array.length(); i++){
        profitList.add(array.getJSONArray(i));
    }
    ArrayList<ArrayList<Integer>> finalList = new ArrayList<>();
    ArrayList<Integer> list1 = new ArrayList<>();
    for (int i = 0; i < profitList.size(); i++){
        JSONArray array1 = profitList.get(i);
        list1 = new ArrayList<>();
        for (int j = 0; j < array1.length(); j++){
            list1.add(array1.getInt(j));
        }
        finalList.add(list1);
    }
}

The ArrayList finalList contains the final output.

like image 165
emilpmp Avatar answered Jan 31 '26 21:01

emilpmp