溫馨提示×

Gson Java怎樣實現(xiàn)自定義適配器

小樊
82
2024-10-22 19:23:43
欄目: 編程語言

在Gson中,要實現(xiàn)自定義適配器,你需要創(chuàng)建一個自定義的TypeAdapter,然后使用GsonBuilder將其注冊到Gson實例中。下面是一個簡單的示例,展示了如何為自定義對象創(chuàng)建一個自定義適配器:

  1. 首先,創(chuàng)建一個自定義類Person
public class Person {
    private String name;
    private int age;

    // 構造函數(shù)、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. 創(chuàng)建一個自定義的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注冊自定義適配器,并創(chuàng)建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
    }
}

現(xiàn)在,你已經(jīng)成功地為Person類創(chuàng)建了一個自定義適配器,并使用它序列化和反序列化了Person對象。

0