Skip to content

Gson – Convert JSON Array to List Example

Gson – Convert JSON array to List example shows how to convert JSON array to a Java List using the Gson library in Java. This example also shows how to convert a JSON array to list using the fromJson method of the Gson class.

How to convert a JSON array to a Java List?

Many times the JSON contains an array that we want to convert to a Java List such as an ArrayList or a LinkedList object. This can be achieved using the fromJson method of the Gson class.

This fromJson method deserializes the given JSON data into an object of the specified type. Consider below given JSON data.

The employee JSON contains known languages as a JSON array. Let’s convert this to a Java list object.

Output

We converted the language JSON array specified as a property value to a Java List object. How about converting a root-level JSON array to a List? Let’s see an example of that.

Now we have a JSON array containing individual employee objects as JSON array elements.

Output

Instead of using the Type, we can also use the toList method of the Arrays class to do the same conversion as given below.

Output

Important Note: The list object returned by the asList method of the Arrays class returns a fixed-sized list backed by the original array, so we can not add or remove elements from it.

However, we can always convert the List to an ArrayList as given below.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.