{
"id": "zhongtong",
"name": "中通快遞",
"order": "371466099000",
"message": "",
"errcode": "0000",
"status": 4,
"data": [
{ "time": "2015-11-23 16:57:06", "content": "南匯二部 的 三計項目 已收件" },
{ "time": "2015-11-23 19:33:57", "content": "快件離開 南匯二部 已發往 上海浦東中心" },
{ "time": "2015-11-23 23:01:46", "content": "快件已經到達 上海浦東中心 上一站是 南匯二部" },
{ "time": "2015-11-23 23:02:36", "content": "快件離開 上海浦東中心 已發往 南京中轉部" }
]
}
public class ExpressResponse {
private String id;
private String name;
private String order;
private String message;
private String errcode;
private int status;
private List
// 依賴: implementation 'com.google.code.gson:gson:2.10.1'
Gson gson = new Gson();
ExpressResponse resp = gson.fromJson(jsonString, ExpressResponse.class);
if ("0000".equals(resp.getErrcode())) {
for (ExpressResponse.Track track : resp.getData()) {
System.out.println(track.getTime() + " - " + track.getContent());
}
}
// 依賴: implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2'
ObjectMapper mapper = new ObjectMapper();
ExpressResponse resp = mapper.readValue(jsonString, ExpressResponse.class);
try {
JSONObject root = new JSONObject(jsonString);
String errcode = root.getString("errcode");
if ("0000".equals(errcode)) {
JSONArray dataArray = root.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject item = dataArray.getJSONObject(i);
String time = item.getString("time");
String content = item.getString("content");
System.out.println(time + " - " + content);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
原最佳回答「整體是一個 jsonObject, data 是一個 jsonArray」正確但過於簡略。上文提供完整實體類、三種主流解析庫用法及 Android 落地建議。