Home » Android » android – Converting JSONarray to ArrayList

android – Converting JSONarray to ArrayList

Posted by: admin March 11, 2020 Leave a comment

Questions:

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":"tb-1370913834.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!

How to&Answers:
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));
   } 
} 

Answer:

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:

ContactModel.java:

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

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

Hope this will help you.

Answer:

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.

Answer:

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.

Answer:

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

Usage:

or

Answer:

In Java 8,

Answer:

Answer:

To make it handy, use POJO.

try like this..

Answer:

Answer:

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


Usage:

or

Answer:

Generic variant

Usage

Answer:

Using Gson