google / gson

A Java serialization/deserialization library to convert Java Objects into JSON and back
Apache License 2.0
23.32k stars 4.28k forks source link

Change default `Date` serialization to ISO 8601 format #2472

Open Marcono1234 opened 1 year ago

Marcono1234 commented 1 year ago

Problem solved by the feature

The current default java.util.Date serialization uses DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US) (source line), which produces output like the following:

"Jan 1, 1970, 1:00:00 AM"

The problem is that this is a locale dependent format intended to be human-readable, and not necessarily to be parsed by computers. The formatting is also dependent on the CLDR data, which changes between Java versions. This has happened for Java 9 already (#1210), and possibly again for Java 20 respectively also older versions using updated CLDR data (https://github.com/google/gson/pull/2450#issuecomment-1652362725, and JDK-8304925).

This leads to backward compatibility issues (#1682), and makes this format unsuitable for transferring data to other applications or services. However, users might not even be aware of these pitfalls until they encounter the issues when switching Java versions.

Related issues:

Feature description

The existing Date deserialization logic already has multiple fallbacks in case parsing fails, including ISO8601Utils, so that might work without issues.

Optional changes:

Risks:

(Note that this is really only a feature request for now; this is not something which has been agreed upon as future Gson change.)

Alternatives

Workarounds

Users can either specify a custom date format using GsonBuilder.setDateFormat(String), or register a custom type adapter for Date to work around these issues.

ckadigkos commented 9 months ago

Hello, Is there any plan someone to work on this ticket anytime soon?

We encountered an issue with the date serialization/deserialization when we mix systems that run on java-8 and java-11 because we rely on the default date format and this is different between version 8 and 9+ of java. Of course we have consider using a custom date formatter but this is a very big change in our system since it's used in almost all of our codebase.