2011-07-28 45 views
21

我有這樣的模式:GSON - 在特定的情況下,自定義序列

public class Student { 
     public String name; 
     public School school; 
} 

public class School { 
     public int id; 
     public String name; 
} 
public class Data { 
     public ArrayList<Student> students; 
     public ArrayList<School> schools; 
} 

我想序列化與GSON數據對象,並獲得這樣的:

{ "students": [{ 
       "name":"name1", 
       "school": "1"   //the id of the scool, not its entire Json 
       }], 
    "school": [{      //the entire JSON 
       "id" : "1", 
       "name": "schoolName" 
      }] 
} 

爲了這一點,我必須使用學生部分的自定義序列化程序,以便Gson只打印學校的ID。但對於學校來說,我必須有正式的序列號。

我該如何處理所有隻有一個Gson對象的東西?

回答

34

您可以編寫自定義序列是這樣的:

public class StudentAdapter implements JsonSerializer<Student> { 

@Override 
public JsonElement serialize(Student src, Type typeOfSrc, 
      JsonSerializationContext context) { 

     JsonObject obj = new JsonObject(); 
     obj.addProperty("name", src.name); 
     obj.addProperty("school", src.school.id); 

     return obj; 
    } 
} 
+0

好吧,我會這樣做,即使有很多領域時很無聊,只有一個外鍵...... –

17

當然,無論你打算序列化這個對象,你需要把它添加到GSON這樣的:

GsonBuilder gsonBuilder = new GsonBuilder(); 
gsonBuilder.registerTypeAdapter(Student.class, new StudentAdapter()); 
return gsonBuilder.create().toJson([YOUR_OBJECT_TO_BE_SERIALIZED]);