要使用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
实现了一个自定义类型适配器。