2016-08-03 36 views
1

我有這樣的JSON:GSON自定義字段Retrofit2解析 - Android電子

Class MyObject { 
    @SerializedName("attributes") 
    Attribues attributes; 
    @SerializedName("first") 
    String first; 
    @SerializedName("second") 
    String second; 
    @SerializedName("third") 
    String third; 
} 

而且

Class Attributes { 
    @SerializedName("date") 
    String date; 
} 

{ 
    "attributes": { 
     "date": "2016-01-01" 
    }, 
    "first": "05:33", 
    "second": "05:50", 
    "third": "07:22" 
} 

通常我們使用GSON改造解析器做這樣的事情來解析此JSON

但我想要做的是:

Class MyObject { 
    // I want date to be here and ignoring the attributes key <--- 
    String date; 
    @SerializedName("first") 
    String first; 
    @SerializedName("second") 
    String second; 
    @SerializedName("third") 
    String third; 
} 

我們該怎麼做?約GSON問題

+0

我認爲你應該做自定義轉換器。看看這個答案 - http://stackoverflow.com/questions/35502079/custom-converter-for-retrofit-2 – Divers

+0

但我使用一個名爲retrofit的android庫,他們使用他們的轉換器,如果它可以在一種方式,我使用他們的轉換器,並使其作爲第二種解決方案。 – MBH

+1

是的,我給你的鏈接正是關於retrofit2自定義json轉換器 – Divers

回答

2

90%具有相同的答案:使用custom TypeAdapter

+0

所以,如果我的類有10+個字段,只有一個字段有問題,我不能只告訴GSon如何轉換該特定的字段,但必須編寫一個完整的爲我的班級定製適配器?我的類有一個Time字段,其類型在C#中是DateTime,但是在Java中是Date。 Newtonsoft.Json將其序列化爲'2016-11-05T14:23:00',但GSon在反序列化對象時爲該字段拋出異常(無時區指示符)。 –

+0

只提供您的日期類型適配器 –