温馨提示×

Gson Java怎样实现自定义适配器

小樊
81
2024-10-22 19:23:43
栏目: 编程语言

在Gson中,要实现自定义适配器,你需要创建一个自定义的TypeAdapter,然后使用GsonBuilder将其注册到Gson实例中。下面是一个简单的示例,展示了如何为自定义对象创建一个自定义适配器:

  1. 首先,创建一个自定义类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;
    }
}
  1. 创建一个自定义的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;
    }
}
  1. 使用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对象。

0