【发布时间】:2017-04-14 03:34:05
【问题描述】:
我正在尝试序列化一个定义了两个 Date 字段的类:
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;
但该字段仍然会导致序列化问题。我什至不确定该字段来自何处,但我怀疑对此的简单解决方案肯定是遥不可及,我只是没有看到。
【问题讨论】:
-
该字段最有可能属于
java.util.Date。我的建议是将数据序列化为Strings 并将其反序列化为Date。 -
我认为发生这种情况是因为您必须将 DataRange 方法和传入 toJson 的参数适用于两个方法签名,创建两个方法有什么意义?
-
我认为这是因为它试图将 dateFormat 序列化为 json。用注解@Transient 标记它。
-
您只需将
dateFormat字段设为static。 -
查看 stackoverflow.com/questions/6873020/gson-date-format 并从此处删除 DateFormat
标签: java json serialization gson