0

I am trying to serialize a class that has two Date fields defined:

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);
    }
}

but using gson.toJson an exception is thrown where multiple

import com.google.gson.Gson

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

results in

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

The problem is exacerbated where I have a class ManyDates which has a field with DateRange as well as another field with an array of DateRange. I have attempted adding the field as a private transient but no luck (also tried with the field as a String type)

private transient java.text.DecimalFormat maximumIntegerDigits;

but the field is still causing issues with the serialization. I'm not sure where that field is even coming from but I suspect a simple solution to this must be just out of reach that I'm just not seeing.

Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105
irregular
  • 1,437
  • 3
  • 20
  • 39
  • The field most likely belongs to `java.util.Date`. My recommendation would be to serialize the data as `String`s and deserialize it into a `Date`. – Jacob G. Apr 14 '17 at 03:37
  • I think this is happens because you have to DataRange method and the argument you pass in toJson applicable for the two methods signature, what is the point of creating two methods? – Fady Saad Apr 14 '17 at 03:43
  • I think that's because it tries to serialize dateFormat to json. Mark it with annotation @Transient. – Maxim Tulupov Apr 14 '17 at 04:42
  • You just have to make the `dateFormat` field `static`. – Lyubomyr Shaydariv Apr 14 '17 at 05:15
  • see http://stackoverflow.com/questions/6873020/gson-date-format and remove the DateFormat from here –  Apr 14 '17 at 05:21
  • @MaximTulupov making dateFormat transient worked. Many thanks! If you post an answer I can mark it as correct. LyumbomyrShaydariv what would making it static do? – irregular Apr 14 '17 at 13:40

1 Answers1

0

In this case gson tries to serialize dateFormat field.

just annotate it with @Transient

Maxim Tulupov
  • 1,621
  • 13
  • 8