簡體   English   中英

帶有Collection字段的對象的GSON自定義序列化程序

[英]GSON custom serializer for an object with a Collection field

我有以下架構:

public class Student {
    String name;
    List<Integer> sequence;
}

我需要我的Student對象的Json

{
    name : "Bruce"
    sequence : {
         index_0 : 5
         index_1 : 2
         index_2 : 7
         index_3 : 8
    }
}

該文檔沒有明確說明如何為集合編寫序列化程序。

您可以創建一個TypeAdapter ,例如:

public static class StudentAdapter extends TypeAdapter<Student> {
    public void write(JsonWriter writer, Student student)
            throws IOException {
        if (student == null) {
            writer.nullValue();
            return;
        }
        writer.beginObject();

        writer.name("name");
        writer.value(student.name);

        writer.name("sequence");
        writeSequence(writer, student.sequence);

        writer.endObject();
    }

    private void writeSequence(JsonWriter writer, List<Integer> seq)
            throws IOException {
        writer.beginObject();
        for (int i = 0; i < seq.size(); i++) {
            writer.name("index_" + i);
            writer.value(seq.get(i));
        }
        writer.endObject();
    }

    @Override
    public Student read(JsonReader in) throws IOException {
        // This is left blank as an exercise for the reader
        return null;
    }
}

然后注冊它

GsonBuilder b = new GsonBuilder();
b.registerTypeAdapter(Student.class, new StudentAdapter());
Gson g = b.create();

如果您使用示例學生運行此操作:

Student s = new Student();
s.name = "John Smith";
s.sequence = ImmutableList.of(1,3,4,7); // This is a guava method
System.out.println(g.toJson(s));

輸出:

{"name":"John Smith","sequence":{"index_0":1,"index_1":3,"index_2":4,"index_3":7}}

GSON支持自定義FieldNamingStrategy

new GsonBuilder().setFieldNamingStrategy(new FieldNamingStrategy() {
    @Override
    public String translateName(java.lang.reflect.Field f) {
        // return a custom field name
    }
});

但這顯然不能涵蓋您的情況,我可以想到的一個簡單的解決方法是使您的sequence列表transient並且具有包含GSON的更正數據的實際序列圖:

public class Student {
    String name;
    transient List<Integer> sequenceInternal;
    Map<String, Integer> sequence;
}

每當您的sequenceInternal對象發生更改時,請將更改寫入序列圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM