006_Gson定制型适配器
生活随笔
收集整理的這篇文章主要介紹了
006_Gson定制型适配器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. Gson使用其內置適配器執行對象的序列化/反序列化。它還支持自定義適配器。我們將討論如何創建自定義適配器以及如何使用它。
2. 創建自定義適配器
2.1. 通過擴展TypeAdapter類并將其傳遞給目標對象的類型來創建自定義適配器。重寫讀取和寫入方法以分別執行自定義反序列化和序列化。
class StudentAdapter extends TypeAdapter<Student> {@Overridepublic Student read(JsonReader reader) throws IOException {...}@Overridepublic void write(JsonWriter writer, Student student) throws IOException {} }3. 注冊自定義適配器
3.1. 使用GsonBuilder注冊自定義適配器和使用創造GSON實例GsonBuilder。
GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Student.class, new StudentAdapter()); Gson gson = builder.create();4. 使用適配器
4.1. Gson現在將使用自定義適配器將Json文本轉換為對象, 反之亦然。
String jsonString = "{\"id\":1, \"name\":\"張三\"}"; Student student = gson.fromJson(jsonString, Student.class); System.out.println(student); jsonString = gson.toJson(student); System.out.println(jsonString);5. 例子
5.1. 新建一個名為GsonAdapter的Java項目, 同時添加相關jar包。
5.2. 新建Student.java
package com.fj.a;public class Student {private int id;private String name;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String toString() {return "Student [id = " + id + ", name = " + name + "]";} }5.3. 新建StudentAdapter.java
package com.fj.a;import java.io.IOException; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter;class StudentAdapter extends TypeAdapter<Student> {@Overridepublic Student read(JsonReader reader) throws IOException {Student student = new Student();reader.beginObject();String fieldname = null;while (reader.hasNext()) {JsonToken token = reader.peek();if (token.equals(JsonToken.NAME)) {fieldname = reader.nextName();}if ("id".equals(fieldname)) {token = reader.peek();student.setId(reader.nextInt());}if ("name".equals(fieldname)) {token = reader.peek();student.setName(reader.nextString());}}reader.endObject();return student;}@Overridepublic void write(JsonWriter writer, Student student) throws IOException {writer.beginObject();writer.name("id");writer.value(student.getId());writer.name("name");writer.value(student.getName());writer.endObject();} }5.4. 新建App.java
package com.fj.a;import com.google.gson.Gson; import com.google.gson.GsonBuilder;public class App {public static void main(String args[]) {GsonBuilder builder = new GsonBuilder();builder.registerTypeAdapter(Student.class, new StudentAdapter());builder.setPrettyPrinting();Gson gson = builder.create();String jsonString = "{\"id\":1, \"name\":\"張三\"}";Student student = gson.fromJson(jsonString, Student.class);System.out.println(student);jsonString = gson.toJson(student);System.out.println(jsonString);} }5.5. 運行App.java
總結
以上是生活随笔為你收集整理的006_Gson定制型适配器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 005_数据绑定
- 下一篇: 007_支持序列化空值