Date: 2010-09-16. Category: com.google.gson examples. Hits: 12K time(s).
In the example below you can see how to convert an array into JSON string. We serialize the array to JSON using theGson.toJson() method. To deserialize a string of JSON into array we use the Gson.fromJson() method.
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
| package org.kodejava.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"}; // // 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 i = 0; i < fibonacci.length; i++) { System.out.print(fibonacci[i] + " "); } System.out.println(""); // // Convert from JSON string to a string array. // String[] weekDays = gson.fromJson(daysJson, String[].class); for (int i = 0; i < weekDays.length; i++) { System.out.print(weekDays[i] + " "); } 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 = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { System.out.print(data[i][j] + " "); } System.out.println(""); } }} |
