Convert from JSONArray to ArrayList<CustomObject> - Android
Asked Answered
R

5

12

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);
Rizzi answered 23/2, 2014 at 0:19 Comment(5)
An arraylist of what? How did you convert it to a JSONArray?Pugnacious
I have created my own object and I fill an array list with 3 objects. I first convert my arraylist to JSONArray and the I want to convert it back to ArrayList. Any tip?Rizzi
Without knowing more about the conversion process, the only tip would be: run the conversion process in reverse.Pugnacious
I edited the post showing how do I convert from ArrayList<OBJECT> to JSONArray. And it works. But how can I convert it back?Rizzi
@DavidStanete Refer my answer below for the simplest way to convert your JsonArray to ArrayList<CustomObject> using Google's Gson library.Stanch
S
44

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.

Stanch answered 24/2, 2014 at 6:27 Comment(1)
SImple and straightforward solution when you are working with custom list objects.Launch
E
3

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

Eleanor answered 23/2, 2014 at 0:28 Comment(2)
This is not what I'm looking for. Please if you can help me, I have editted the question.Rizzi
The frustrating fact is that JSONArray is already using a ArrayList inside, but that one is private.Wrongheaded
P
1

Unfortunately, this will require a little work on your part. Gson does not support deserializing generic collections of arbitrary objects. The Gson User Guide topic Serializing and Deserializing Collection with Objects of Arbitrary Types list three options for doing what you want. To quote the relevant parts of the guide:

You can serialize the collection with Gson without doing anything specific: toJson(collection) would write out the desired output. However, deserialization with fromJson(json, Collection.class) will not work since Gson has no way of knowing how to map the input to the types. Gson requires that you provide a genericised version of collection type in fromJson. So, you have three options:

Option 1: Use Gson's parser API (low-level streaming parser or the DOM parser JsonParser) to parse the array elements and then use Gson.fromJson() on each of the array elements. This is the preferred approach. Here is an example that demonstrates how to do this.

Option 2: Register a type adapter for Collection.class that looks at each of the array members and maps them to appropriate objects. The disadvantage of this approach is that it will screw up deserialization of other collection types in Gson.

Option 3: Register a type adapter for MyCollectionMemberType and use fromJson with Collection<MyCollectionMemberType> This approach is practical only if the array appears as a top-level element or if you can change the field type holding the collection to be of type Collection<MyCollectionMemberType>.

See the docs for details on each of the three options.

Pugnacious answered 23/2, 2014 at 2:18 Comment(0)
S
0

we starting from conversion [ JSONArray -> List < JSONObject > ]

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;
}

next create generic version replacing array.getJSONObject(i++) with POJO

example :

public <T> static List<T> getJSONObjectListFromJSONArray(Class<T> forClass, JSONArray array) 
        throws JSONException {
  ArrayList<Tt> tObjects = new ArrayList<>();
  for (int i = 0; 
           i < (array != null ? array.length() : 0);           
           tObjects.add( (T) createT(forClass, array.getJSONObject(i++))) 
       );
  return tObjects;
}

private static T createT(Class<T> forCLass, JSONObject jObject) {
   // instantiate via reflection / use constructor or whatsoever 
   T tObject = forClass.newInstance(); 
   // if not using constuctor args  fill up 
   // 
   // return new pojo filled object 
   return tObject;
}
Skullcap answered 9/11, 2016 at 15:23 Comment(0)
F
0

Try this,

ArrayList<**YOUCLASS**> **YOURARRAY** = 
new Gson().fromJson(oldJSONArray.toString(), 
new TypeToken<List<**yourClass**>>(){}.getType());
Frog answered 2/4, 2019 at 9:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.