kramer65
kramer65

Reputation: 53843

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?

Upvotes: 36

Views: 42151

Answers (1)

Rahul
Rahul

Reputation: 45060

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

Upvotes: 66

Related Questions