編輯:關於 Android 程式設計
Gson 是 Google 出品、在 Android 開發中廣泛使用的 JSON 處理庫。它能輕鬆地在 Java 物件與 JSON 字串之間雙向轉換,下面透過實例說明常見資料結構的處理方式。
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Main {
public static class Student {
private String name;
int age;
private String address;
private Date dateOfBirth;
public Student() { }
public Student(String name, int age, String address, Date dateOfBirth) {
this.name = name;
this.age = age;
this.address = address;
this.dateOfBirth = dateOfBirth;
}
// 省略 getter / setter
}
public static void main(String[] args) {
Gson gson = new Gson();
/* 陣列轉成 JSON 串 */
int[] numbers = {1, 1, 2, 3, 5, 8, 13};
String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
String numbersJson = gson.toJson(numbers);
String daysJson = gson.toJson(days);
/* List 轉成 JSON 串,元素為字串 */
List names = new ArrayList();
names.add("Alice");
names.add("Bob");
names.add("Carol");
names.add("Mallory");
String jsonNames = gson.toJson(names);
/* List 轉成 JSON 串,元素為物件 */
Student a = new Student("Alice", 20, "Apple St", new Date(2000, 10, 1));
Student b = new Student("Bob", 23, "Banana St", null);
Student c = new Student("Carol", 42, "Grape St", new Date(2000, 5, 21));
Student d = new Student("Mallory", 24, "Mango St", null);
List students = new ArrayList();
students.add(a);
students.add(b);
students.add(c);
students.add(d);
String jsonStudents = gson.toJson(students);
// 把 JSON 串還原成 Student 物件的集合
Type type = new TypeToken>(){}.getType();
List studentList = gson.fromJson(jsonStudents, type);
for (Student student : studentList) {
System.out.println("student.getName() = " + student.getName());
}
/* Map 轉成 JSON 串,value 為字串 */
Map colors = new HashMap();
colors.put("BLACK", "#000000");
colors.put("RED", "#FF0000");
colors.put("GREEN", "#008000");
colors.put("BLUE", "#0000FF");
colors.put("YELLOW", "#FFFF00");
colors.put("WHITE", "#FFFFFF");
String jsonmap = gson.toJson(colors);
// 把 JSON 串還原成 Map
Type type1 = new TypeToken
執行後可觀察到以下規律:
1、單個物件(Object)對應的 JSON 串是一個 JsonObject,冒號「:」前是 Java 物件的變數名,冒號後則是變數值。
2、陣列與 List 對應的 JSON 串是一個 JsonArray。
3、Map 對應的 JSON 串也是 JsonObject,冒號前是 Map 的 Key,冒號後是 Map 的 Value。
關鍵在於判斷冒號「:」後 Value 的資料型別,對應到 Java 物件的欄位型別即可。以下是一段典型的後端回傳資料:
{
"success": true,
"data": {
"list": [
{"dataType": 0, "distance": 435.24, "isFav": 0, "parkCode": "0270000558",
"parkName": "武漢金融港路場", "parkID": 558, "remark": "", "parkType": 0,
"responsible": "", "responseTel": "13297062676", "consultTel": "",
"coordinateX": 114.428102, "coordinateY": 30.462254, "coordinateEntrance": "",
"rateInfo": "工作日", "introduce": "", "appState": 3, "paymentNoticeMinute": 0,
"rentCount": 0, "rentSwitch": 0, "spaceCount": 42, "totalCount": 42,
"imageName": "", "fullImage": "", "unitFee": 0.0, "unit": 0, "isRoadSide": 0,
"rentOvertimeTimes": 0.0, "reservationKeepTime": 0, "supportPayType": 0,
"address": "光谷大道金融港", "state": 1}
]
}
}
對應的 Park 資料類只需按欄位型別宣告屬性即可:
package com.hust.map;
public class Park {
int dataType;
int rentCount;
int parkCode;
String parkName; // 停車場名字
int parkID;
String remark;
int parkType;
String responsible;
String responseTel;
String consultTel;
double coordinateX; // 經度
double coordinateY; // 緯度
String coordinateEntrance;
String rateInfo; // 收費標準
String introduce;
int appState;
int paymentNoticeMinute;
int spaceCount; // 可租車位
int totalCount; // 總車位
String imageName;
String fullImage;
int reservationKeepTime;
int isRoadSide;
double rentOvertimeTimes;
double unitFee;
int unit;
int rentSwitch;
int supportPayType;
int isFav;
double distance; // 距離
String address; // 地址
int state;
// 省略 constructor 與 getter / setter
}
由於最外層的 data 是一個包含 list 陣列的結構,可用 HashMap 承接,再取出其中的列表:
package com.hust.map;
import java.util.ArrayList;
import java.util.HashMap;
public class DataFromNetWork {
boolean success;
HashMap> data;
}
DataFromNetWork mDataFromNetWork = mGson.fromJson(mParksString, DataFromNetWork.class); ArrayListmParksList = mDataFromNetWork.data.get("list");
掌握以上要領,就能在 Gson 的協助下,於 JSON 與各種 Java 資料結構之間輕鬆穿梭。
Android TextView 控制項使用介紹
TextView 的作用TextView 是最基礎的文字顯示控制項,類似其他 UI 框架中的 Label 或 TextBlock,常用來顯示單行或多行文字。常用屬性and
Android 短信加密實戰:發送加密短信與解密本地短信
短信加密這類功能由於初學者的學習需求相對較少,網上簡單的 Demo 參考並不多。本文分享一個完整的短信加密範例,涵蓋發送加密短信與解密本地短信兩大功能,並附上全部程式碼。
Android 七大佈局方式完整解析:Linear、Relative、Table、List、Grid、Absolute、Tab
前面我們已經對 Android 程式的執行原理與佈局檔有了基本認識,也用「Hello World!」驗證過一次。在往下深入之前,有個該補的基礎得先補完:View 的幾種佈
Android 開發筆記:RecyclerView 水平多行列表的加頭加尾封裝
RecyclerView 本身並不提供 addHeaderView / addFooterView 這樣的 API,如果我們需要一個既能水平多行排列、又支持頭尾布局的列表