Android中gson、jsonobject解析JSON的方法详解

2019-12-10 19:07:26王冬梅

3.3.2 JSON数组的解析(原生类)

Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};
//序列化(serialization)
//将整数数组转换为JSON数组
gson.toJson(ints); // ==> [1,2,3,4,5]
//将字符串数组转换为JSON数组
gson.toJson(strings); // ==> ["abc", "def", "ghi"]
// 反序列化(Deserialization)
// 将JSON数组转换为原生类数组
// ints2、string2与ints、strings相等
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); 
String[] strings2 = gson.fromJson("["abc", "def", "ghi"]",String[].class); 

3.3.3 JSON数组的解析(自定义类)

//对于类似于2.2中的jsonData,包含3个Student对象
//与原生类不同,需要借助TypeToken获得期望解析成的数据类型
//下列代码运行后,students包含三个Student对象
Gson gson = new Gson();
List<Student> students;
students = gson.fromJson(jsonData, new TypeToken<List<Student>>(){}.getType()); // ==>[stu0,stu1,stu2] 

3.4 更多方法

•GSON的 简便之处 在于其可以将字符串 自动映射 为原生或自定义对象,从而不需要手动编写代码进行解析。

•GSON的 更多方法 可以阅读GSON在github上的用法介绍,README.md -> user guide。

以上内容给大家介绍了Android中gson、jsonobject解析JSON的方法详解,希望对大家有所帮助。



注:相关教程知识阅读请移步到Android开发频道。