Fixed DefaultDateTypeAdapter nullability issue and JSON primitives contract (#1100)

* Fixed DefaultDateTypeAdapter nullability issue and JSON primitives contract

Regression in:

* b8f616c939 - Migrate DefaultDateTypeAdapter to streaming adapter (#1070)

Bug reports:

* https://github.com/google/gson/issues/1096 - 2.8.1 can't serialize and deserialize date null (2.8.0 works fine)
* https://github.com/google/gson/issues/1098 - Gson 2.8.1 DefaultDateTypeAdapter is not null safe.

* Fixed DefaultDateTypeAdapter nullability on write
This commit is contained in:
Lyubomyr Shaydariv 2017-09-18 09:49:13 +03:00 committed by inder123
parent f0aa1118e9
commit 7a9fd5962d
2 changed files with 21 additions and 2 deletions

View File

@ -84,6 +84,10 @@ final class DefaultDateTypeAdapter extends TypeAdapter<Date> {
// See issue 162
@Override
public void write(JsonWriter out, Date value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
synchronized (localFormat) {
String dateFormatAsString = enUsFormat.format(value);
out.value(dateFormatAsString);
@ -92,8 +96,9 @@ final class DefaultDateTypeAdapter extends TypeAdapter<Date> {
@Override
public Date read(JsonReader in) throws IOException {
if (in.peek() != JsonToken.STRING) {
throw new JsonParseException("The date should be a string value");
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
Date date = deserializeToDate(in.nextString());
if (dateType == Date.class) {

View File

@ -161,6 +161,20 @@ public class DefaultDateTypeAdapterTest extends TestCase {
} catch (IllegalArgumentException expected) { }
}
public void testNullValue() throws Exception {
DefaultDateTypeAdapter adapter = new DefaultDateTypeAdapter(Date.class);
assertNull(adapter.fromJson("null"));
assertEquals("null", adapter.toJson(null));
}
public void testUnexpectedToken() throws Exception {
try {
DefaultDateTypeAdapter adapter = new DefaultDateTypeAdapter(Date.class);
adapter.fromJson("{}");
fail("Unexpected token should fail.");
} catch (IllegalStateException expected) { }
}
private void assertFormatted(String formatted, DefaultDateTypeAdapter adapter) {
assertEquals(toLiteral(formatted), adapter.toJson(new Date(0)));
}