Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSONArray to List with Gson?

In my Android project I'm trying to convert a received JSONArray to a List. With the help of this SO answer I got a bit further. I now have the following code:

Gson gson = new Gson(); JSONArray jsonArray = NetworkUtilities.getData("mymodeldata"); Type listType = new TypeToken<List<MyModel>>(){}.getType(); List<MyModel> myModelList = gson.fromJson(jsonArray, listType); 

Unfortunately it complaints at the last line that the method fromJson(String, Type) in the type Gson is not applicable for the arguments (JSONArray, Type). I don't really know how to solve this.

Does anybody know how I can solve this?

like image 666
kramer65 Avatar asked Oct 02 '13 09:10

kramer65


People also ask

Can we convert JSONArray to JSONObject?

We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.

Can we convert JSON array to list in Java?

Java For TestersWe can convert a JSON array to a list using the ObjectMapper class. It has a useful method readValue() which takes a JSON string and converts it to the object class specified in the second argument.

How get values from JSONArray?

You can easy get a JSON array element by key like this: var value = ArrName['key_1']; //<- ArrName is the name of your array console. log(value);


1 Answers

If you see the answer there, you can notice that the first parameter in the fromJson() method was a String(the json object). Try to use the toString() on the JsonArray like this:-

List<MyModel> myModelList = gson.fromJson(jsonArray.toString(), listType); 
like image 154
Rahul Avatar answered Oct 07 '22 17:10

Rahul