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:
parent
f0aa1118e9
commit
7a9fd5962d
@ -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) {
|
||||
|
@ -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)));
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user