简体   繁体   中英

GSON custom serializer for an object with a Collection field

I have the following schema:

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

I need the Json of my Student object to be

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

The documentation doesn't clearly say how to write a serializer for collections.

You could create a TypeAdapter , something like:

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;
    }
}

And then register it with

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

If you run this with an example student:

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));

Output:

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

GSON supports a custom FieldNamingStrategy :

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

But this obviously does not cover your case, an easy workaround i can think of would be to make your sequence list transient and have an actual sequence map with the corrected data for GSON:

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

and whenever a change occurs on your sequenceInternal object, write the changes through to the sequence map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM