Java如何将数组转换为JSON?
在下面的示例中,您可以看到如何将数组转换为JSON字符串。我们使用Gson.toJson()方法将数组序列化为JSON。要将JSON字符串反序列化为数组,我们使用Gson.fromJson()方法。
package org.nhooo.example.google.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"}; //创建一个新的Gson实例 Gson gson = new Gson(); //将数字数组转换为JSON字符串。 String numbersJson = gson.toJson(numbers); //将字符串数组转换为JSON字符串 String daysJson = gson.toJson(days); System.out.println("numbersJson = " + numbersJson); System.out.println("daysJson = " + daysJson); //从JSON字符串转换为int的原始数组。 int[] fibonacci = gson.fromJson(numbersJson, int[].class); for (int number : fibonacci) { System.out.print(number + " "); } System.out.println(""); //从JSON字符串转换为字符串数组。 String[] weekDays = gson.fromJson(daysJson, String[].class); for (String weekDay : weekDays) { System.out.print(weekDay + " "); } System.out.println(""); //将多维数组转换为JSON int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}}; String json = gson.toJson(data); System.out.println("Data = " + json); //将JSON字符串转换为int的多维数组。 int[][] dataMap = gson.fromJson(json, int[][].class); for (int[] i : dataMap) { for (int j : i) { System.out.print(j + " "); } System.out.println(""); } } }
这是我们的代码结果:
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依赖
<!-- http://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.0/gson-2.8.0.jar --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency>