2016-05-23 49 views
1

我有一個Java bean類,與@Parcel(Parcel.Serialization.BEAN)和GSON的@SerializedName在某些領域註解時:失蹤領域展開與Parceler庫地塊對象

Question.java:

@Parcel(Parcel.Serialization.BEAN) 
public class Question { 

    private Integer id; 
    private String title; 
    private String description; 
    private User user; 

    @SerializedName("other_model_id") 
    private Integer otherModelId, 

    @SerializedName("created_at") 
    private Date createdAt; 

    // ----- Getters and setters ----- 
} 

當我m開始ShowQuestionActivity,我將我的包裹question對象傳遞給它(其中question已將所有字段設置爲):

Intent intent = new Intent(context, ShowQuestionActivity.class); 
intent.putExtra("extra_question", Parcels.wrap(question)); 
startActivity(intent); 

ShowQuestionActivity,我得到 「extra_question」 從我intent對象:

Question question = Parcels.unwrap(intent.getParcelableExtra(Constants.EXTRA_QUESTION)); 

但Parceler返回我只有標題和描述(字符串)......所有其他領域都

結束語對象與Parcels.wrap(question)和調試工作完全與Parcels.unwrap(question)展開,但將其通過意圖後,似乎「失去」自己的價值觀,但我不能找到問題...


我Parceler設置如下:

模塊的build.gradle

dependencies { 
    compile 'org.parceler:parceler-api:1.1.4' 
    apt 'org.parceler:parceler:1.1.4' 
} 

而且在我的項目的的build.gradle

dependencies { 
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' 
} 
+0

您的設置看起來正確。你所有的getters/setters是否被正確地聲明?用戶是用'@ Parcel'來註釋的,你是否爲Date添加了一個'@ ParcelPropertyConverter'? –

+0

@JohnEricksen,我的getter和setter被正確地聲明。用戶使用'@Parcel(Parcel.Serialization.BEAN)'註釋了getter和setter,並且我還沒有爲Date添加'@ ParcelPropertyConverter',因爲我現在不打算使用這個字段。它是否會阻止Parceler生成Parcel類? –

+0

我試圖弄清楚發生了什麼,當我添加'@ ParcelProperty(「Gson @SerializedName字段」)時,它按預期工作,但它警告我反思。我真的需要爲每個字段編寫@ParcelProperty嗎?那反思呢? –

回答

2

隨着BEAN系列化戰略,Parceler需要要被包裝的未包裝的類中的每個物業配套getter和setter方法。

此外,默認情況下未映射的屬性(如Date)要求您編寫轉換器或將這些類型映射到@ParcelClass。見http://parceler.org/#custom_serialization

下面是一個代碼示例:

@Parcel(Parcel.Serialization.BEAN) 
public class Question { 

    private Integer id; 
    private String title; 
    private Date createdAt; 

    // id is included in the Parcelable because it has matching getter and setters 
    public Integer getId() { return id; } 
    public void setId(Integer id) { this.id = id; } 

    // title is not included as the setter is missing (it's not a true bean property) 
    public String getTitle() { return title; } 

    // createdAt will issue an error as it is not a defined type, and no converter is defined. 
    public Date getCreatedAt() { return createdAt; } 
    public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } 
} 

值得注意的是,如果你滿意GSON編組內部類狀態,你可能要考慮使用默認FIELD系列化戰略,而不是BEAN與配對非私人領域。這種技術不需要任何特定的getter和setter組合。

+0

哇!謝謝你注意到這一點。我不知道我需要手動實現getter和setter。在圖書館看起來像事後看起來。爲什麼生成的類不能處理這個問題? – w3bshark

+0

這僅限於BEAN封口類型。使用默認的FIELD類型,這些字段將被直接使用並避免獲取/設置者。 –

+0

是的,明白了。我使用Parceler的Realm來處理一些對象,只有那些對象需要BEAN序列化,所以我只更新了這些對象。謝謝您的幫助。非常感激! – w3bshark