带有Collection字段的对象的GSON自定义序列化程序

时间:2015-05-04 13:05:10

标签: java json serialization collections gson

我有以下架构:

{"<UserInformation xmlns=''> was not expected."}

我需要var data = {"Books:"....}; var indianBooks = _.filter(data.Books.History, function(book) { return _.contains(book.Tags, "Indian"); }) 对象的Json为

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

The documentation没有明确说明如何为集合编写序列化程序。

2 个答案:

答案 0 :(得分:3)

您可以创建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}}

答案 1 :(得分:0)

GSON支持自定义FieldNamingStrategy

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

这显然不能涵盖您的情况,我能想到的一个简单的解决方法是制作您的sequence列表transient并拥有实际< / em>带有GSON校正数据的序列图:

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

当您的sequenceInternal对象发生更改时,请将更改写入序列图。