本文记录的是如何使用Gson处理Array类型数据,
包括将Array对象序列化为Json串以及将Json串反序列化为Array对象.
下面的示例是将数组元素序列化为Json串,如下所示:
Serialization:
1 2 3 4 5
| Gson gson = new Gson(); int[] ints = {1, 2, 3, 4, 5}; String[] strings = {"abc", "def", "ghi"}; System.out.println("json_string: " + gson.toJson(ints)); System.out.println("json_string: " + gson.toJson(strings));
|
示例中控制台会输出:
1 2
| json_string: [1,2,3,4,5] json_string: ["abc","def","ghi"]
|
数组的反序列化如下所示:
Deserialization:
1 2 3 4 5
| Gson gson = new Gson(); String intsStr = "[1,2,3,4,5]"; String stringsStr = "[\"abc\",\"def\",\"ghi\"]"; int[] ints2 = gson.fromJson(intsStr, int[].class); String[] strings2 = gson.fromJson(stringsStr, String[].class);
|
可以设置断点查看数组中元素。
另外: Gson also support multi-dimensional arrays, with arbitrarily
complex element types.
参考:
Gson
User Guide
目前已转行教育行业,欢迎加微信交流:CaryaLiu