Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from JSONArray to ArrayList<CustomObject> - Android

I converted an ArrayList to an JSONArray. How can I convert it back?

The final result must be an ArrayList. Thank you in advance.

EDIT:

This is how I convert the ArrayList to JSONArray:

String string_object= new Gson().toJson(MyArrayList<OBJECT>);
JSONArray myjsonarray = new JSONArray(string_object);
like image 327
stanete Avatar asked Feb 23 '14 00:02

stanete


People also ask

How to Convert JSON file to Array in Java?

In order to parse the JSON, I use the delimited to use newline since BufferedReader has a method readLine that we could directly use to get each JSONObject. Once I get each valid JSON from each line, I create JSONObject and add it to the ArrayList. I then iterate each JSONObject in the ArrayList and print out the ...

How to map JSON Array to list in Java?

Reading JSON from a File final ObjectMapper objectMapper = new ObjectMapper(); List<Language> langList = objectMapper. readValue( new File("langs. json"), new TypeReference<List<Language>>(){}); langList. forEach(x -> System.

How can we convert a list to the JSON array in Java?

We can convert a list to the JSON array using the JSONArray. toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.


2 Answers

You can convert your JsonArray or json string to ArrayList<OBJECT> using Gson library as below

ArrayList<OBJECT> yourArray = new Gson().fromJson(jsonString, new TypeToken<List<OBJECT>>(){}.getType());

//or

ArrayList<OBJECT> yourArray = new Gson().fromJson(myjsonarray.toString(), new TypeToken<List<OBJECT>>(){}.getType());

Also while converting your ArrayList<OBJECT> to JsonArray, no need to convert it to string and back to JsonArray

 JsonArray myjsonarray = new Gson().toJsonTree(MyArrayList<OBJECT>).getAsJsonArray();

Refer Gson API documentation for more details. Hope this will be helpful.

like image 142
Purushotham Avatar answered Sep 23 '22 13:09

Purushotham


JSONArray is just a subclass of object, so if you want to get the JSONObjects out of a JSONArray into some other form, JSONArray doesn't have any convenient way to do it, so you have to get each JSONObject and populate your ArrayList yourself.

Here is a simple way to do it:

ArrayList<JSONObject> arrayList = new ArrayList(myJSONArray.length());
for(int i=0;i < myJSONArray.length();i++){
    arrayList.add(myJSONArray.getJSONObject(i));
}

EDIT:

OK, you edited your code to show that you are using GSON. That is a horse of a different color. If you use com.google.gson.JsonArray instead of JSONArray, you can use the Gson.fromJson() method to get an ArrayList.

Here is a link: Gson - convert from Json to a typed ArrayList

like image 32
David C Adams Avatar answered Sep 23 '22 13:09

David C Adams