In the example below you can see how to convert an array into JSON string. We serialize the array to JSON using the Gson.toJson()
method. To deserialize a string of JSON into array we use the Gson.fromJson()
method.
package org.kodejava.gson;
import com.google.gson.Gson;
public class ArrayToJson {
public static void main(String[] args) {
int[] numbers = {1, 1, 2, 3, 5, 8, 13};
String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
// Create a new instance of Gson
Gson gson = new Gson();
// Convert numbers array into JSON string.
String numbersJson = gson.toJson(numbers);
// Convert strings array into JSON string
String daysJson = gson.toJson(days);
System.out.println("numbersJson = " + numbersJson);
System.out.println("daysJson = " + daysJson);
// Convert from JSON string to a primitive array of int.
int[] fibonacci = gson.fromJson(numbersJson, int[].class);
for (int number : fibonacci) {
System.out.print(number + " ");
}
System.out.println();
// Convert from JSON string to a string array.
String[] weekDays = gson.fromJson(daysJson, String[].class);
for (String weekDay : weekDays) {
System.out.print(weekDay + " ");
}
System.out.println();
// Converting multidimensional array into JSON
int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}};
String json = gson.toJson(data);
System.out.println("Data = " + json);
// Convert JSON string into multidimensional array of int.
int[][] dataMap = gson.fromJson(json, int[][].class);
for (int[] i : dataMap) {
for (int j : i) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Here is our code result:
numbersJson = [1,1,2,3,5,8,13]
daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
1 1 2 3 5 8 13
Sun Mon Tue Wed Thu Fri Sat
Data = [[1,2,3],[3,4,5],[4,5,6]]
1 2 3
3 4 5
4 5 6
Maven Dependencies
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.11.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
And how to convert a JSON to an Array using Jackson?
Hi Leonardo,
To convert JSON to Array using Jackson library you can do the following: