阅读量:0
在Gson中,要实现自定义适配器,你需要创建一个自定义的TypeAdapter
,然后使用GsonBuilder
将其注册到Gson
实例中。下面是一个简单的示例,展示了如何为自定义对象创建一个自定义适配器:
- 首先,创建一个自定义类
Person
:
public class Person { private String name; private int age; // 构造函数、getter和setter方法 public Person(String name, int age) { this.name = name; this.age = age; } 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; } }
- 创建一个自定义的
TypeAdapter<Person>
:
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; } }
- 使用
GsonBuilder
注册自定义适配器,并创建Gson
实例:
import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class Main { public static void main(String[] args) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Person.class, new PersonAdapter()); Gson gson = gsonBuilder.create(); // 使用自定义适配器将Person对象序列化为JSON字符串 Person person = new Person("John Doe", 30); String jsonString = gson.toJson(person); System.out.println(jsonString); // 输出:{"name":"John Doe","age":30} // 使用自定义适配器将JSON字符串反序列化为Person对象 String inputJson = "{\"name\":\"Jane Doe\",\"age\":25}"; Person deserializedPerson = gson.fromJson(inputJson, Person.class); System.out.println(deserializedPerson.getName() + " " + deserializedPerson.getAge()); // 输出:Jane Doe 25 } }
现在,你已经成功地为Person
类创建了一个自定义适配器,并使用它序列化和反序列化了Person
对象。