java - 如何使用 GSON 进行自定义序列化?

标签 java json gson

我有一个案例想使用 GSON 自定义序列化功能。

class Student{
   public String name;
   public int rollNumber;

   public Student(String name, int rollNumber){
        this.name = name;
        this.rollNumber = rollNumber;
   }

   public int getRollNumber(){
       return this.rollNumber;
   }

   public String getName(){
       return this.name;
   }


}
class School{

    public Student[] students;

    public School(Student[] students){
          this.students = students;
    }


   public Students[] getStudents(){
       return this.students;
   }

}

当我这样做的时候

private static final Gson GSON = new GsonBuilder().disableHtmlEscaping().create();

Student[] students = new Student[2];

students[0] = new Student("sam", 1);

students[1] = new Student("tom", 2);

School school = new School(students);

GSON.toJson(school);

我得到这样的输出:

[{"name":"sam","rollNumer":1},{"name":"tom","rollNumer":2}]

但我希望它是:

["student":{"name":"sam","rollNumer":1},"student":{"name":"tom","rollNumer":2}]

如何使用 GSON 自定义序列化实现这一点?

我试过了thisthis .但没有太大帮助。

最佳答案

这个

["student":{"name":"sam","rollNumer":1},"student":{"name":"tom","rollNumer":2}]

不是有效的 JSON(您可以使用 jsonlint 等在线工具自行验证)。详见JSON specification :

对象的定义:

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

数组的定义:

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

值的定义:

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

您的输出定义了一个 JSON 数组,但该数组中的对象没有用大括号正确括起来。正确的表示应该是这样的:

[{"student":{"name":"sam","rollNumer":1}}, {"student":{"name":"tom","rollNumer":2}}]

可以用这个简单的 Gson TypeAdapter 生成:

class StudentAdapter extends TypeAdapter<Student> {

    @Override
    public void write(final JsonWriter writer, final Student student)
            throws IOException {
        if (student == null) {
            writer.nullValue();
            return;
        }

        writer.beginObject();
        writer.name("student");
        writer.beginObject();
        writer.name("name");
        writer.value(student.getName());
        writer.name("rollNumber");
        writer.value(student.getRollNumber());
        writer.endObject();
        writer.endObject();
    }

    @Override
    public Student read(final JsonReader reader) throws IOException {
        if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();
            return null;
        }

        final Student student = new Student();
        reader.beginObject();
        reader.nextName(); // discard the 'student' wrapper property
        reader.beginObject();
        while (reader.hasNext()) {
            final String attrName = reader.nextName();
            if ("name".equals(attrName)) {
                student.setName(reader.nextString());
            } else if ("rollNumber".equals(attrName)) {
                student.setRollNumber(reader.nextInt());
            }
        }
        reader.endObject();
        reader.endObject();

        return student;
    }
}

测试方法:

@Test
public void testWriteSchoolsAsJSONWithGsonAndCustomOutput()
        throws Exception {
    final Gson gson = new GsonBuilder().registerTypeAdapter(Student.class,
            new StudentAdapter()).create();

    Student[] students = new Student[2];
    students[0] = new Student("sam", 1);
    students[1] = new Student("tom", 2);

    School school = new School(students);

    final String outputJson = gson.toJson(school);
    System.out.println(outputJson);

    school = gson.fromJson(outputJson, School.class);
    System.out.println(school);
}

和“相关”输出:

{"students":[{"student":{"name":"sam","rollNumber":1}},{"student":{"name":"tom","rollNumber":2}}]}

关于java - 如何使用 GSON 进行自定义序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16462057/

相关文章:

javascript - Java 和 Javascript 之间的加密和解密将不起作用

android - 通过索引从 gson 获取值

android - gradle android studio 2.3 : failed to resolve 'com.google.code.gson:gson:2.8.0'

json - 关于 EBNF 表示法和 JSON 的问题

javascript - 无需键即可调用 JSON 的元素

java - Moshi 有像 Gson 这样的运行时类型适配器工厂吗?

JavaFX primaryStage 删除 windows 边框?

java - Dropwizard 多个 Assets 包冲突

java - 线程突然终止

java - ClientRequest,如何正确地将POJO序列化为json数据?找不到内容类型应用程序/json 类型 : 的编写器