Skip to content

Gson – Convert Java List to JSON Array Example

Gson – Convert Java List to JSON array example shows how to convert a Java List to a JSON array using the Gson library. This example also shows how to do it using the toJson method of the Gson class.

How to convert Java List to JSON array?

We can use the toJson method of the Gson class to convert a Java List to a JSON array.

This method serializes the specified object into the JSON representation.

Here is an example that converts a List of employee objects to an equivalent JSON representation.

Output

As we can see from the output, each Java list element becomes a JSON array element.

If we want to convert a Java List to JsonElement, we can use the toJsonTree method instead of the toJson method.

This method serializes the specified object into a tree of JsonElement objects.

Output

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

About the author

Leave a Reply

Your email address will not be published.