you can easily read JSONArray
into ArrayList
of type class to which JSONArray
is representing. Thank is GSON
this entire process can be done in a single line of code. as shown bellow.
ArrayList<MyItem> items2 = (new Gson()).fromJson(result,new TypeToken<ArrayList<MyItem>>() {}.getType());
Lets assume you are given with a JSONArray
of type MyItem
above line of code will convert JSONArray
into the ArrayList
of type MyItem
.
I have written a sample code, that you may get a better picture.
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class MyTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<MyItem> items = new ArrayList<>();
for (int i = 0; i < 5; i++) {
MyItem item = new MyItem();
item.setRate("rate_"+i);
item.setSomeCode("some_"+i);
items.add(item);
}
String result = (new Gson()).toJson(items);
System.out.println(""+result);
ArrayList<MyItem> items2 = (new Gson()).fromJson(result,new TypeToken<ArrayList<MyItem>>() {}.getType());
System.out.println(""+items2.size());
}
}
class MyItem {
private String rate;
private String someCode;
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
public String getSomeCode() {
return someCode;
}
public void setSomeCode(String someCode) {
this.someCode = someCode;
}
}
Output
[
{
"rate": "rate_0",
"someCode": "some_0"
},
{
"rate": "rate_1",
"someCode": "some_1"
},
{
"rate": "rate_2",
"someCode": "some_2"
},
{
"rate": "rate_3",
"someCode": "some_3"
},
{
"rate": "rate_4",
"someCode": "some_4"
}
]
this JSONArray
is converted into ArrayList
of type MyItem
I have also written some answers on this topic which you may want to check for further information on serialization
and de-serialization
using GSON
library
Example_1
Example_2
Example_3
Example_4