Make Rfc3339DateJsonAdapter null-safe (#910)

* Move delegate to private final

* Make Rfc3339DateJsonAdapter null-safe

Resolves #723
This commit is contained in:
Zac Sweers
2019-09-11 07:22:02 -04:00
committed by Jesse Wilson
parent c820314107
commit 1978581b3d
3 changed files with 17 additions and 5 deletions

View File

@@ -23,7 +23,7 @@ import java.util.Date;
* The new class is {@code com.squareup.moshi.adapters.Rfc3339DateJsonAdapter}.
*/
public final class Rfc3339DateJsonAdapter extends JsonAdapter<Date> {
com.squareup.moshi.adapters.Rfc3339DateJsonAdapter delegate
private final com.squareup.moshi.adapters.Rfc3339DateJsonAdapter delegate
= new com.squareup.moshi.adapters.Rfc3339DateJsonAdapter();
@Override public Date fromJson(JsonReader reader) throws IOException {

View File

@@ -23,8 +23,8 @@ import java.util.Date;
/**
* Formats dates using <a href="https://www.ietf.org/rfc/rfc3339.txt">RFC 3339</a>, which is
* formatted like {@code 2015-09-26T18:23:50.250Z}. To use, add this as an adapter for {@code
* Date.class} on your {@link com.squareup.moshi.Moshi.Builder Moshi.Builder}:
* formatted like {@code 2015-09-26T18:23:50.250Z}. This adapter is null-safe. To use, add this as
* an adapter for {@code Date.class} on your {@link com.squareup.moshi.Moshi.Builder Moshi.Builder}:
*
* <pre> {@code
*
@@ -35,12 +35,19 @@ import java.util.Date;
*/
public final class Rfc3339DateJsonAdapter extends JsonAdapter<Date> {
@Override public synchronized Date fromJson(JsonReader reader) throws IOException {
if (reader.peek() == JsonReader.Token.NULL) {
return reader.nextNull();
}
String string = reader.nextString();
return Iso8601Utils.parse(string);
}
@Override public synchronized void toJson(JsonWriter writer, Date value) throws IOException {
if (value == null) {
writer.nullValue();
} else {
String string = Iso8601Utils.format(value);
writer.value(string);
}
}
}

View File

@@ -63,6 +63,11 @@ public final class Rfc3339DateJsonAdapterTest {
.isEqualTo("\"1937-01-01T11:40:27.870Z\"");
}
@Test public void nullSafety() throws Exception {
assertThat(adapter.toJson(null)).isEqualTo("null");
assertThat(adapter.fromJson("null")).isNull();
}
private Date newDate(
int year, int month, int day, int hour, int minute, int second, int millis, int offset) {
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));