在 app 程序里实现和服务器的交互基本都是提供 json 作为数据传输格式
今天我们就来学习一下通过 Gson 对象来操作 JSON 数据的技巧
打开 Gradle scripts -> build.gradle (Module: app)
在 dependencies 里添加如下依赖项目
implementation 'com.google.code.gson:gson:2.8.2'
点击右上角的 Sync Now 下载库
不同的数据结构需要建立不同的结构对象去解析
数组结构需要使用 List 去解析
未知 Key/Value 结构需要使用 Map 去解析
解析不一定成功,必须放到 try catch 里运行
定义结构对象 JsonObject,使用 Gson 的 fromJson 方法去解析
String json = "..."; // json 字符串 Gson gson = new Gson(); JsonObject res = gson.fromJson(json, JsonObject.class);
为了方便使用,我们将 Gson 封装了一下
后面的示例都是以 TFJson 对象为例的
public class TFJson {
/**
* 将json 转成对象
* @param jsonResult
* @param cla
* @param <T>
* @return
*/
public static <T> T jsonDecode(String jsonResult, Class<T> cla) {
T t = null;
try {
Gson gson = new Gson();
t = gson.fromJson(jsonResult, cla);
}
catch (Exception e) {
e.printStackTrace();
}
return t;
}
/**
* 将Json字符串转成list
* @param json
* @param <T>
* @return
*/
public static <T> ArrayList<T> jsonDecodeToArray(String json) {
ArrayList<T> t = null;
try {
Gson gson = new Gson();
t = new ArrayList<T>();
Type type = new TypeToken<ArrayList<T>>() {
}.getType();
t = gson.fromJson(json, type);
}
catch (Exception e) {
e.printStackTrace();
}
return t;
}
/**
* 将对象转成Json字符串
* @param obj
* @return
*/
public static String jsonEncode (Object obj) {
Gson gson = new Gson();
return gson.toJson(obj);
}
}json 结构
{
status: "ok",
message: "success"
}java 结构对象
class JsonObject {
public String status;
public String message;
}java 解析
JsonObject res = TFJson.jsonDecode(json, JsonObject.class);
java 解析
Map<String, String> res = new HashMap<>(); res = TFJson.jsonDecode(json, res.getClass());
json 结构
[
{"id":"12345", "name":"张3"},
{"id":"22345", "name":"李4"}
]java 结构对象
class JsonObject {
public String id;
public String name;
}java 解析
List<JsonObject> res = TFJson.jsonDecodeToArray(json);
java 解析
List<Map<String, String>> res = new ArrayList<>(); res = TFJson.jsonDecode(json, res.getClass());
json 结构
{
"status": "ok",
"message": "success",
"data": {
"id": 12345,
"name": "super man"
}
}java 结构
class JsonObject {
public String status;
public String message;
public SubJsonObject data;
}
class SubJsonObject {
int id;
String name;
}java 解析
JsonObject res = TFJson.jsonDecode(json, JsonObject.class);
一般情况下我们需要判断 JSON 的数据结构是单一对象还是对象数组,然后使用 jsonDecode 或者 jsonDecodeToArray 去解析
通过 Map 方式解析不需要建立结构对象,但是解析的类型全部是 String 类型,不便于后面的操作
针对复合结构可以建立复合结构对象去解析