2015-05-04 43 views

回答

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}} 
+2

//这是留给读者的一个练习......不错的一个:) @ durron597 – Kaushik

+2

@Kaushik他只问如何序列化,而不是反序列化:-) – durron597

+0

很酷的答案,它总是很棒学习新东西! – epoch

0

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

并且每当您的发生更改时对象,将更改写入序列图。