Converting JSONarray to ArrayList
Asked Answered
D

23

141

I am downloading a JSON string and converting it to JSONArray. Im putting it into a listview and need to be able to delete from that listview later, and since JSONArray has no .remove method (Thanks Obama), I am trying to convert it to an arraylist.

here is my JSON (the array.toString()):

[
    {
         "thumb_url":"tb1370913834.jpg",
         "event_id":"15","count":"44",
         "event_tagline":"this is a tagline",
         "event_name":"5th birthday",
         "event_end":"1370919600",
         "event_start":"1370876400"
    }
]

I need to get it into an array and be able to call the strings by their respective keys. Appreciate any help!

Doited answered 11/6, 2013 at 5:54 Comment(3)
When you say keys, doesn't that imply a Dictionary (Map in Android) of some sort? An array will be index-based. Take a look at developer.android.com/reference/java/util/Map.html for how to create and use.Exclude
Can a map be used to populate a listview with a custom baseadapter? Id rather not use indexes in case the JSON ever changes order.Doited
ListView will get objects from the adapter by index, so in any case you will need to maintain the list in some order. If you want to maintain the order of the keys (and know what the keys are at compile time), you can hard-code an array of those keys in the order you like and use that for your ordering when fetching from the Map.Exclude
B
202
ArrayList<String> listdata = new ArrayList<String>();     
JSONArray jArray = (JSONArray)jsonObject; 
if (jArray != null) { 
   for (int i=0;i<jArray.length();i++){ 
    listdata.add(jArray.getString(i));
   } 
} 
Berky answered 11/6, 2013 at 5:55 Comment(6)
And listdata.add(jArray.optJSONObject(i)); if your listdata is a JSONObject arrayList. ArrayList<JSONObject> listdata = new ArrayList<JSONObject>(); Abirritant
Good snippet. Just in case if anyone wants: there is a helper class that converts JSONObject/JSONArray to a standard Map/List on the github gist.github.com/codebutler/2339666Wallacewallach
Why not use an ArrayList<Object>?Erbes
How may i handle the Json Array is empty. please reply me bro.Simoom
Is there any other way to do this without loop?Metacenter
@K.Sopheak, Streams (Java 8 & up) can do.Decarbonize
C
82

I've done it using Gson (by Google).

Add the following line to your module's build.gradle:

dependencies {
  // ...
  // Note that `compile` will be deprecated. Use `implementation` instead.
  // See https://stackoverflow.com/a/44409111 for more info
  implementation 'com.google.code.gson:gson:2.8.2'
}

JSON string:

private String jsonString = "[\n" +
            "        {\n" +
            "                \"id\": \"c200\",\n" +
            "                \"name\": \"Ravi Tamada\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c201\",\n" +
            "                \"name\": \"Johnny Depp\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c202\",\n" +
            "                \"name\": \"Leonardo Dicaprio\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c203\",\n" +
            "                \"name\": \"John Wayne\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c204\",\n" +
            "                \"name\": \"Angelina Jolie\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"female\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c205\",\n" +
            "                \"name\": \"Dido\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"female\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c206\",\n" +
            "                \"name\": \"Adele\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"female\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c207\",\n" +
            "                \"name\": \"Hugh Jackman\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c208\",\n" +
            "                \"name\": \"Will Smith\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c209\",\n" +
            "                \"name\": \"Clint Eastwood\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c2010\",\n" +
            "                \"name\": \"Barack Obama\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c2011\",\n" +
            "                \"name\": \"Kate Winslet\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"female\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c2012\",\n" +
            "                \"name\": \"Eminem\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        }\n" +
            "    ]";

ContactModel.java:

public class ContactModel {
     public String id;
     public String name;
     public String email;
}

Code for converting a JSON string to ArrayList<Model>:

Note: You have to import java.lang.reflect.Type;:

// Top of file
import java.lang.reflect.Type;

// ...

private void parseJSON() {
    Gson gson = new Gson();
    Type type = new TypeToken<List<ContactModel>>(){}.getType();
    List<ContactModel> contactList = gson.fromJson(jsonString, type);
    for (ContactModel contact : contactList){
        Log.i("Contact Details", contact.id + "-" + contact.name + "-" + contact.email);
    }
}

Hope this will help you.

Cultigen answered 4/12, 2015 at 5:29 Comment(6)
THREE LINES...DONE! I think this should have been the accepted answer since (a) it's only three lines of code that work beautifully, and (b) few of the answers actually perform a typed translation from JSONArray to List<CustomObject>. Thank you!Hartnett
It must be a JSONArray, the JSONElement seems not work. so, use the getAsJsonArray() method appearently. Thank you!Rightly
Exactly what I needed, thanks! Note: You have to import these: java.lang.reflect.Type; com.google.gson.reflect.TypeToken;Conciseness
Awesome, This should have been the accepted answer!. ThanksPasskey
this does not work saying init of typetoken is protectedMesnalty
This is chaos when having date and Time objects like LocalDate and LocalDateTimeBrewing
R
8

I have fast solution. Just create a file ArrayUtil.java

import java.util.ArrayList;
import java.util.Collection;
import org.json.JSONArray;
import org.json.JSONException;

public class ArrayUtil
{
    public static ArrayList<Object> convert(JSONArray jArr)
    {
        ArrayList<Object> list = new ArrayList<Object>();
        try {
            for (int i=0, l=jArr.length(); i<l; i++){
                 list.add(jArr.get(i));
            }
        } catch (JSONException e) {}

        return list;
    }

    public static JSONArray convert(Collection<Object> list)
    {
        return new JSONArray(list);
    }

}

Usage:

ArrayList<Object> list = ArrayUtil.convert(jArray);

or

JSONArray jArr = ArrayUtil.convert(list);
Reisfield answered 5/12, 2016 at 20:49 Comment(3)
Wha I do if need to return a ArrayList<String>Henryhenryetta
I think it's not possible to cast ArrayList<Object> to ArrayList<String>Reisfield
Kudos to this answer. U solved my day! I spent 2 hrs trying to fix this. Actually my problem was I wanted to put the converted JSONArray to a list so I could put the List in a HashMap, so this util worked for me pretty well. Thanks @Vasilii SuricovFishwife
I
8

In Java 8,

IntStream.range(0,jsonArray.length()).mapToObj(i->jsonArray.getString(i)).collect(Collectors.toList())
Intertidal answered 18/9, 2017 at 10:28 Comment(2)
The only problem with this is that JSONArray.getString(...) throws an exception which has to be handled inside of the mapping, so you end up with List<String> listOfStrings = IntStream.range(0, array.length()).mapToObj(i -> { try { return array.getString(i); } catch (JSONException e) { throw new AssertionFailedError("JSONArray is not a list of Strings! " + e.getMessage()); } }).collect(Collectors.toList()); which is not that elegant any more. So I'll go with a foreach :)Wouldst
This is the best answer here (imho) but would be elegant if there was a way to not need to access the jsonArray reference more than once.Kufic
C
7

try this way Simply loop through that, building your own array. This code assumes it's an array of strings, it shouldn't be hard to modify to suit your particular array structure.

JSONArray jsonArray = new JSONArray(jsonArrayString);
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
    list.add( jsonArray.getString(i) );
Cestus answered 11/6, 2013 at 6:3 Comment(0)
E
7

Instead of converting the JSON string to an ArrayList or even a Map, you can just create a JSONObject itself. This object has the ability to get string values by key, as you want and also to remove objects.

To create a JSONObject from a properly formatted JSON string, you simply call the appropriate constructor.

JSONObject json = new JSONObject(jsonString);
Exclude answered 11/6, 2013 at 6:7 Comment(2)
The problem I run into with this solution in particular, is that when dealing with JSONObject's and JSONArray's is they throw JSONException's. Sometimes it's handy to pass the contents of a JSONArray to a function that shouldn't have to be aware of JSON.Scotfree
I agree. I would use the JSONObject as part of parsing the JSON text into a usable model object. Any JSONException that is raised would indicate a problem with the source JSON, meaning you can't parse it into a JSONArray or JSONObject, let alone a different model object.Exclude
A
4
 JSONArray array = new JSONArray(json);
 List<JSONObject> list = new ArrayList();
 for (int i = 0; i < array.length();list.add(array.getJSONObject(i++)));
Anthony answered 2/12, 2014 at 10:17 Comment(0)
M
3

I have fast solution. Just create a file ArrayUtil.java

ObjectMapper mapper = new ObjectMapper(); 
List<Student> list = Arrays.asList(mapper.readValue(jsonString, Student[].class));

Usage:

ArrayList<Object> list = ArrayUtil.convert(jArray);

or

JSONArray jArr = ArrayUtil.convert(list);
Manzanares answered 20/6, 2019 at 6:17 Comment(0)
F
2

To make it handy, use POJO.

try like this..

List<YourPojoObject> yourPojos = new ArrayList<YourPojoObject>();

JSONObject jsonObject = new JSONObject(jsonString);
YourPojoObject yourPojo = new YourPojoObject();
yourPojo.setId(jsonObject.getString("idName"));
...
...

yourPojos.add(yourPojo);
Footnote answered 11/6, 2013 at 6:28 Comment(0)
F
2

if you want to extract data form JSON string array, here is my working code. change parameter as your data.


PoJo class

public class AllAppModel {
    private String appName;
    private String packageName;
    private int uid;
    private boolean isSelected;
    private boolean isSystemApp;
    private boolean isFav;
}

Extract your data using below line of code

try {
    JSONArray jsonArr = new JSONArray("Your json string array");
    List<AllAppModel> lstExtrextData = new ArrayList<>();
    for (int i = 0; i < jsonArr.length(); i++) {
        JSONObject jsonObj = jsonArr.getJSONObject(i);
        AllAppModel data = new AllAppModel();
        data.setAppName(jsonObj.getString("appName"));
        data.setPackageName(jsonObj.getString("packageName"));
        data.setUid(jsonObj.getInt("uid"));
        data.setSelected(jsonObj.getBoolean("isSelected"));
        data.setSystemApp(jsonObj.getBoolean("isSystemApp"));
        data.setFav(jsonObj.getBoolean("isFav"));
        lstExtrextData.add(data);
    }
} catch (JSONException e) {
    e.printStackTrace();
}

it will return you List of PoJo class object.

Faus answered 20/4, 2020 at 11:1 Comment(0)
N
2

Just going by the original subject of the thread:

converting jsonarray to list (used jackson jsonarray and object mapper here):

ObjectMapper mapper = new ObjectMapper();
JSONArray array = new JSONArray();
array.put("IND");
array.put("CHN");
List<String> list = mapper.readValue(array.toString(), List.class);
Namecalling answered 29/5, 2020 at 17:24 Comment(0)
W
2

If the Json object consists an array of strings, then there is a way where we need not even use the JSONArray.

if the Json is not in string format, we can convert the json into a string. Now if Json string is:

String value = "[\"value1\",\"value2\"]";

Then we can use to get the List of String:

List<String> result = new Gson().fromJson(value, List.class);
Winglet answered 11/3, 2021 at 13:32 Comment(0)
Z
2

with GSON and Kotlin you just need this:

    val arr = Gson().fromJson(jsonArrayInString, Array<T>::class.java)
Zelikow answered 26/5, 2021 at 9:38 Comment(0)
L
1

Using Gson

    List<Student> students = new ArrayList<>();
    JSONArray jsonArray = new JSONArray(stringJsonContainArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        Student student = new Gson().fromJson(jsonArray.get(i).toString(), Student.class);
        students.add(student);
    }
    return students;
Lapidify answered 11/10, 2019 at 11:39 Comment(0)
B
1

Java 8 style

   JSONArray data = jsonObject.getJSONArray("some-node");

   List<JSONObject> list = StreamSupport.stream(data.spliterator(), false)
                .map(e -> (JSONObject)e)
                .collect(Collectors.toList());
Brawny answered 14/7, 2020 at 11:54 Comment(1)
Not working... Getting error - Type mismatch: cannot convert from Object to List<JSONObject>Pierro
C
1

With Kotlin, you can avoid a loop by wrapping the JSONArray with a MutableList, e.g.

val artistMetadata = player.metadata.optJSONArray("artist")
val artists = MutableList<String>(artistMetadata.length()) { i -> artistMetadata.getString(i)}
Cam answered 4/2, 2021 at 18:54 Comment(0)
A
1

Single line code that I used to convert json array to ArrayList for the below listed json string stored in a variable named classData.

List<String> names = new Gson().fromJson(classData.getAsJsonObject("result").getAsJsonArray("names").toString(), new TypeToken<List<String>>(){}.getType());
{   
    "result": {
        "id": "104297",
        "class": "Chemistry",
        "total": 57,
        "names": [
            "Alex",
            "Dan",
            "Rex",
            "Tony",
            "Elizabeth"
        ],
        ...
    }
}
Angarsk answered 21/5, 2021 at 18:36 Comment(0)
S
0
public static List<JSONObject> getJSONObjectListFromJSONArray(JSONArray array) 
        throws JSONException {
  ArrayList<JSONObject> jsonObjects = new ArrayList<>();
  for (int i = 0; 
           i < (array != null ? array.length() : 0);           
           jsonObjects.add(array.getJSONObject(i++))
       );
  return jsonObjects;
}
Sanatory answered 9/11, 2016 at 14:30 Comment(0)
P
0

Generic variant

public static <T> List<T> getList(JSONArray jsonArray) throws Exception {

    List<T> list = new ArrayList<>(jsonArray.length());

    for (int i = 0; i < jsonArray.length(); i++) {

        list.add((T)jsonArray.get(i));
    }

    return list;

}

//Usage

List<String> listKeyString = getList(dataJsonObject.getJSONArray("keyString"));
Pintsize answered 6/8, 2019 at 15:20 Comment(0)
W
0
ArrayList<String> listdata = new ArrayList<String>();     
JSONArray jArray = (JSONArray)jsonObject; 
if (jArray != null) { 
 listdata.addAll(jArray);
}

@simplified

Week answered 21/5, 2020 at 5:47 Comment(0)
C
0

A simpler Java 8 alternative:

JSONArray data = new JSONArray(); //create data from this -> [{"thumb_url":"tb-1370913834.jpg","event_id":...}]

List<JSONObject> list = data.stream().map(o -> (JSONObject) o).collect(Collectors.toList());
Complimentary answered 7/8, 2020 at 13:14 Comment(1)
Tried this. Does not work. Getting error - Type mismatch: cannot convert from Object to List<JSONObject>Pierro
A
0
public static List<String> convertJsonArrayToStringList(JsonArray ja){
    
    List<String> result = new ArrayList<String>();     
    for(JsonElement je: ja)
        result.add(je.getAsString());
    
    return result;
    
}
Ascender answered 5/3, 2021 at 1:28 Comment(0)
D
0

This can do (Java >= 8):

    // Functional (variable)
    Function<JSONArray, ArrayList<String>> convert = jsonArray -> (ArrayList<String>) jsonArray.stream()
        .map(item -> item.toString())
        .collect(Collectors.toList());

    // Call
    convert.apply(jsonArray);


    // Regular method (OOP)
    private Function<JSONArray, ArrayList<String>> convert() {
        return jsonArray -> (ArrayList<String>) jsonArray.stream()
            .map(item -> item.toString())
            .collect(Collectors.toList());
   }

   // Call
   convert().apply(jsonArray);

Decarbonize answered 20/11, 2021 at 17:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.