Search code examples
javaarraysjsonlistorg.json

How to get a value which is a List from a JSONObject in Java


I have a following JSON:

{"data":["str1", "str2", "str3"]}

I want to get a List, i.e. ["str1", "str2", "str3"]

My code is:

JSONObject json = new JSONObject();
List list = new ArrayList();
...
// adding data in json
...
list = (List) json.get("data");

This is not working.


Solution

  • You can customize a little bit of code like it

    public static void main(String[] args) throws ParseException {
            String data = "{\"data\":[\"str1\", \"str2\", \"str3\"]}";
            JSONObject json = new JSONObject(
                    data);
             
            JSONArray jasonArray = json.getJSONArray("data");
            List list = new ArrayList();
    
            int size = jasonArray.length();
            int i = 0;
            while (i < size) {
                list.add(jasonArray.get(i));
                i++;
            }
    
            System.out.println(list);
    
        }