Gson-自定义类型适配器

通过之前的文章,我们已经知道Gson有许多内置的类型适配器,它们对不同类型的数据进行序列化/反序列化。其实,Gson还支持自定义类型适配器。本文将讨论如何创建自定义适配器以及如何使用它。

1 创建自定义类型适配器语法

通过继承TypeAdapter类并将其传递给目标对象类型来创建自定义适配器。重写read() 和 write() 方法来做分别自定义反序列化,序列化操作。

class StudentAdapter extends TypeAdapter<Student> { 
   @Override 
   public Student read(JsonReader reader) throws IOException { 
      ... 
   } 
   
   @Override 
   public void write(JsonWriter writer, Student student) throws IOException { 
   } 
}

2 注册自定义类型适配器语法

使用GsonBuilder注册自定义适配器和使用创造GSON实例GsonBuilder。

GsonBuilder builder = new GsonBuilder(); 
builder.registerTypeAdapter(Student.class, new StudentAdapter()); 
Gson gson = builder.create(); 

3 使用自定义类型适配器语法

现在我们可以使用自定义适配器将Json文本转换为对象,或者把对象转换为Json文本。

String jsonString = "{\"name\":\"eric\", \"rollNo\":1}"; 
Student student = gson.fromJson(jsonString, Student.class); 
System.out.println(student);  
jsonString = gson.toJson(student); 
System.out.println(jsonString);

4 自定义类型适配器的示例

4.1 编写核心类

MainApp:

package com.yiidian.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class MainApp {

    public static void main(String args[]) {

        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Student.class, new StudentAdapter());
        builder.setPrettyPrinting();
        Gson gson = builder.create();

        String jsonString = "{\"name\":\"eric\", \"rollNo\":1}";
        Student student = gson.fromJson(jsonString, Student.class);
        System.out.println(student);

        jsonString = gson.toJson(student);
        System.out.println(jsonString);
    }

}

class StudentAdapter extends TypeAdapter<Student> {
    @Override
    public Student read(JsonReader reader) throws IOException {
        Student student = new Student();
        reader.beginObject();
        String fieldname = null;

        while (reader.hasNext()) {
            JsonToken token = reader.peek();

            if (token.equals(JsonToken.NAME)) {
                //get the current token
                fieldname = reader.nextName();
            }

            if ("name".equals(fieldname)) {
                //move to next token
                token = reader.peek();
                student.setName(reader.nextString());
            }

            if("rollNo".equals(fieldname)) {
                //move to next token
                token = reader.peek();
                student.setRollNo(reader.nextInt());
            }
        }
        reader.endObject();
        return student;
    }

    @Override
    public void write(JsonWriter writer, Student student) throws IOException {
        writer.beginObject();
        writer.name("name");
        writer.value(student.getName());
        writer.name("rollNo");
        writer.value(student.getRollNo());
        writer.endObject();
    }
}

class Student {
    private int rollNo;
    private String name;

    public int getRollNo() {
        return rollNo;
    }

    public void setRollNo(int rollNo) {
        this.rollNo = rollNo;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String toString() {
        return "Student[ name = "+name+", roll no: "+rollNo+ "]";
    }
}

4.2 运行测试