Gson 是一個 Java 庫,可用於將 Java 對象轉換爲 JSON 字符串表示。
1 Gson 實例
1.1 class 和 string 轉化
JSONObject是個好東東,可以將java class 分分鐘變成json 傳遞
語法說明keyword: toJson and fromJson
eg1:
// 簡單的bean轉爲json
String s1 = gson.toJson(student1);
System.out.println("簡單Bean轉化爲Json===" + s1);
// json轉爲簡單Bean
Student student = gson.fromJson(s1, Student.class);
System.out.println("Json轉爲簡單Bean===" + student);
// 結果:
// 簡單Bean轉化爲Json==={"id":1,"name":"李坤","birthDay":"Jun 22, 2012 8:27:52 AM"}
// Json轉爲簡單Bean===Student [birthDay=Fri Jun 22 08:27:52 CST 2012, id=1,
https://blog.csdn.net/lk_blog/article/details/7685169
1.2 看一個複雜點的例子
//Gson:class轉成json的常用方法getJson
public JSONObject getJson() {
Gson gson = new Gson();
try {
return new JSONObject(gson.toJson(this));
} catch (JSONException e) {
e.printStackTrace();
return new JSONObject();
}
}
//調用
private final BlockingQueue<CloudAgentSecondaryDevice> mSDIQueue = new LinkedBlockingQueue<>();
CloudAgentAttachedMonitor mon = new CloudAgentAttachedMonitor();
// set json value
mon.setRefreshRate(refresh);
mon.setResolution(resolution);
...
mSDIQueue.add(mon);
List<CloudAgentSecondaryDevice> availableDevices = new ArrayList<>();
synchronized (mSDIQueue) {
//將BlockingQueue轉成List; 用基類指向多種類型的子類
mSDIQueue.drainTo(availableDevices);
}
if (!availableDevices.isEmpty()) {
CloudAgentSecondaryDeviceInfoEvent sdiEvt = new
CloudAgentSecondaryDeviceInfoEvent();
//List<CloudAgentSecondaryDevice>
sdiEvt.setAttachedDevices(availableDevices);
CloudAgentInfoMessage caiMsg = new CloudAgentInfoMessage(SDI_FRM_TAG +
String.valueOf(sdiEvt.hashCode()), sdiEvt);
//GSOn的強大,將list中的多個class,都轉成了json data string.eg:ip mic+ monitor+camera
System.out.println(caiMsg.getJson().toString());
}
2 annotation
語法說明keyword:
@Expose註解:作用,變量暴露可見,所有需要序列化的variable都要有,沒有它的variable不能序列化.required。
@SerializedName註解: 作用,改名.optional。
如果peer回來的和本地不匹配,可以改動這個而不改代碼,但是有個缺點,改名則搜索不容易正確找到。
3 JSONObject 和gson 關係
兩種方式都可以將class 轉成string。gson.toJson 轉成 json string. JSONObject 轉成json 對象,當使用string的時候,使用toString.
eg2: JSONObject temp = JSONObject(gson.toJson(student1));
String s1 = temp.toString();
System.out.println("簡單Bean轉化爲Json===" + s1);