服務端返回數據結構
{
"slay": "1",
"rs": {
"total": 6,
"rows": [
{"name": "張三", "phone": "111111"},
{"name": "李四", "phone": "222222"}
]
}
}
實體類設計(與 JSON 結構完全對應)
public class Response {
private String slay;
private Rs rs;
// getter/setter
}
public class Rs {
private int total;
private List rows;
// getter/setter
}
public class Row {
private String name;
private String phone;
// getter/setter
}
Gson 解析核心代碼
Gson gson = new Gson();
Response response = gson.fromJson(jsonString, Response.class);
List dataList = response.getRs().getRows(); // 直接獲取列表數據
// 綁定 RecyclerView
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new ContactAdapter(dataList));
動態新增數據並自動刷新
// 新增聯系人後
dataList.add(0, newRow); // 插入到頂部
adapter.notifyItemInserted(0); // 局部刷新,帶動畫
// 或整體刷新
adapter.notifyDataSetChanged();
常見坑與避坑指南
- 字段名不匹配:JSON 鍵含下劃線(
user_name)而 Java 駝峰(userName),需加 @SerializedName("user_name") 註解。
- 數組為 null 導致 NPE:實體類初始化
rows = new ArrayList<>(),或使用 Optional 判空。
- 日期格式:配置
GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create() 統一解析。
- 大數據量解析卡頓:子線程解析 +
runOnUiThread 更新 UI,或使用 Gson Streaming API 流式解析。
最佳實踐總結
- 定義實體類時嚴格對應 JSON 層級,字段類型用包裝類(
Integer)防止 null 拆箱崩潰。
- 使用
GsonBuilder 統一配置字段命名策略、日期格式、null 序列化策略。
- 網絡層封裝
BaseResponse 泛型,實現統一錯誤碼處理與數據解耦。