2017-04-14 85 views
0

我試圖序列化有定義的兩個Date領域類:GSON:序列化一類具有兩個日期字段

import com.google.gson.annotations.Expose; 
import java.util.Date; 

public class DateRange { 
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
    @Expose 
    public Date startDate; 
    @Expose 
    public Date endDate; 

    public DateRange(Date startDate, Date endDate) { 
     this.startDate = startDate; 
     this.endDate = endDate; 
    } 
    public DateRange(String startDate, String endDate) throws ParseException{ 
     this.startDate = dateFormat.parse(startDate); 
     this.endDate = dateFormat.parse(endDate); 
    } 
} 

但使用gson.toJson拋出一個異常,其中多個

import com.google.gson.Gson 

Gson gson = new Gson() 
gson.toJson(new DateRange("2011-11-11", "2012-11-11")) 

結果在

java.lang.IllegalArgumentException: class java.text.DecimalFormat declares multiple JSON fields named maximumIntegerDigits 
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:166) 

問題是加劇了,我有一個類ManyDates它有一個字段DateRange以及另一個字段的數組DateRange。我試圖添加字段作爲private transient,但沒有運氣(也試圖與該領域的String型)

private transient java.text.DecimalFormat maximumIntegerDigits; 

,但現場仍然引起與序列化問題。我不確定那個領域是從哪裏來的,但我懷疑這個簡單的解決方案一定是遙不可及的,我只是沒有看到。

+0

該字段最有可能屬於'java.util.Date'。我的建議是將數據序列化爲「字符串」並將其反序列化爲「日期」。 –

+0

我認爲這是因爲你必須將DataRange方法和你傳遞給Json的參數適用於兩個方法簽名,創建兩個方法有什麼意義? –

+0

我認爲這是因爲它試圖將dateFormat序列化爲json。用註釋@Transient標記它。 –

回答

0

在這種情況下,gson試圖序列化dateFormat字段。

只需用@Transient對其進行註釋

相關問題