how to convert JSONArray to JSONObject list in java

‮‬https://www.lautturi.com
how to convert JSONArray to JSONObject list in java

Method 1

/**
 * @author lautturi.com 
 * Java example:  JSONArray to list of JSONObject in java
 */

import java.util.*;
import org.json.JSONArray;
import org.json.JSONObject;

public class Lautturi {
	public static void main(String[] args) {
		String jsonString = "[{\"id\":111,\"name\":\"Lautturi\"}, {\"id\":112,\"name\":\"James\"}]";
		JSONArray data = new JSONArray(jsonString);

		List<JSONObject> list = new ArrayList<JSONObject>();
		
		for(Object o : data) {
			// JSONObject object = ((JSONObject) o);
			list.add((JSONObject) o);
		}
		
		System.out.print(list);
	}
}

output:

[{"name":"Lautturi","id":111}, {"name":"James","id":112}]

Method 2

/**
 * @author lautturi.com 
 * Java example:
 */

import java.util.*;
import org.json.JSONArray;
import org.json.JSONObject;

public class Lautturi {
	public static void main(String[] args) {
		String jsonString = "[{\"id\":111,\"name\":\"Lautturi\"}, {\"id\":112,\"name\":\"James\"}]";
		JSONArray jsonArr = new JSONArray(jsonString);
		
		List<JSONObject> list = new ArrayList<JSONObject>();
		
		for(int i=0;i<jsonArr.length();i++) {
			list.add(jsonArr.getJSONObject(i));
		}
		
		System.out.print(list);
	}
}

output:

[{"name":"Lautturi","id":111}, {"name":"James","id":112}]
Created Time:2017-10-03 13:38:36  Author:lautturi