要使用Gson庫在Java中實現自定義類型適配器,你需要創建一個自定義的TypeAdapter
,并在其中編寫序列化和反序列化的邏輯。以下是一個簡單的示例,展示了如何為自定義類Person
實現自定義類型適配器:
pom.xml
文件中添加以下依賴:<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
Person
:public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getter 和 setter 方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
PersonAdapter
:import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
public class PersonAdapter extends TypeAdapter<Person> {
@Override
public void write(JsonWriter out, Person value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
out.beginObject();
out.name("name").value(value.getName());
out.name("age").value(value.getAge());
out.endObject();
}
@Override
public Person read(JsonReader in) throws IOException {
if (in.peek() == null) {
in.nextNull();
return null;
}
Person person = new Person("", 0);
in.beginObject();
while (in.hasNext()) {
String name = in.nextName();
switch (name) {
case "name":
person.setName(in.nextString());
break;
case "age":
person.setAge(in.nextInt());
break;
default:
in.skipValue();
break;
}
}
in.endObject();
return person;
}
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main {
public static void main(String[] args) {
// 創建一個Person對象
Person person = new Person("John Doe", 30);
// 創建一個GsonBuilder對象,并注冊自定義類型適配器
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Person.class, new PersonAdapter());
// 使用Gson實例進行序列化和反序列化
Gson gson = gsonBuilder.create();
String json = gson.toJson(person);
System.out.println("Serialized JSON: " + json);
Person deserializedPerson = gson.fromJson(json, Person.class);
System.out.println("Deserialized Person: " + deserializedPerson.getName() + ", " + deserializedPerson.getAge());
}
}
運行上述代碼,你將看到如下輸出:
Serialized JSON: {"name":"John Doe","age":30}
Deserialized Person: John Doe, 30
這樣,你就成功地為自定義類Person
實現了一個自定義類型適配器。