GSON Array and Multi Dimensional Array Example
Arrays are a very basic structure and can be serialized or deserialized using GSON API. Here we show you how to serialize and deserialize and array or a multi dimensional array to and from its JSON representation.
Array
This example serializes and deserializes an array to and from JSON representation.
Gson gson = new GsonBuilder().create();
int[] intArray = {1, 2, 3, 4};
String[] stringArray = {"abc", "def", "ghi"};
// serialization
gson.toJson(intArray); // => [1,2,3,4]
gson.toJson(stringArray); // => ["abc","def","ghi"]
// deserialization
int[] intArray2 = gson.fromJson("[1,2,3,4]", int[].class);
String[] stringArray2 = gson.fromJson("[\"abc\",\"def\",\"ghi\"]", String[].class);
Multi Dimensional Array
This examples demonstrates how to serialize and deserialize a multi dimensional array to and from JSON representation.
Gson gson = new GsonBuilder().create();
int[][] multiIntArray = new int[][]{{1, 2, 3}, {4, 5, 6}};
// serialization
gson.toJson(multiIntArray); // => [[1,2,3],[4,5,6]]
// deserialization
int[][] intArray2 = gson.fromJson("[[1,2,3],[4,5,6]]", int[][].class);