others-how to use gson to convert json string to a java array?

1. Purpose

In this post, I will demonstrate how to use gson to convert json string to a java array.

2. Solution

2.1 What is gson?

Google Gson is a simple Java-based library to serialize Java objects to JSON and vice versa. It is an open-source library developed by Google.

It can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Import gson library:

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->

Or using gradle:

// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation 'com.google.code.gson:gson:2.8.7'

2.2 How to convert json string to array?

Gson gson = new Gson();

String jsonArray = "[\"Android\",\"Java\",\"PHP\"]";
String[] strings = gson.fromJson(jsonArray, String[].class);
List<String> stringList = gson.fromJson(jsonArray, new TypeToken<List<String>>()

The syntax for TypeToken is:

new TypeToken<List<XXX>>() // replace XXX with your class type

More about TypeToken:

public class TypeToken extends Object Represents a generic type T. Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime. For example, to create a type literal for List, you can create an empty anonymous inner class:

TypeToken<List<String>> list = new TypeToken<List<String>>() {};

This syntax cannot be used to create type literals that have wildcard parameters, such as Class<?> or List<? extends CharSequence>.

3. Summary

In this post, I demonstrated how to do array transform in gson using TypeToken. That’s it, thanks for your reading.