TimeZoneJsonAdapter extends JsonAdapter<TimeZone> { @Override public TimeZone fromJson(JsonReader reader) throws IOException { String timeZoneName = null; Double utcOffset = null; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (reader.peek() == Token.NULL) { reader.skipValue(); continue; } if ("name" .equals(name)) { timeZoneName = reader.nextString(); } else if ("utc_offset" .equals(name)) { utcOffset = reader.nextDouble(); } else { reader.skipValue(); } } reader.endObject(); if (timeZoneName != null && utcOffset != null) return new TimeZone(timeZoneName, utcOffset); return null; } TimeZoneJsonAdapter(); @Override TimeZone fromJson(JsonReader reader); @Override void toJson(JsonWriter writer, TimeZone timeZone); @Override String toString(); static final JsonAdapter.Factory FACTORY; }
@Test public void ignoresInvalidTimeZone() throws Exception { JsonAdapter<TimeZone> adapter = timeZoneAdapter(TimeZone.class); assertThat(adapter.fromJson("{\"name\":\"hey\",\"utc_offset\":null}")).isNull(); assertThat(adapter.fromJson("{\"name\":null,\"utc_offset\":null}")).isNull(); assertThat(adapter.fromJson("{\"latitude\":null,\"longitude\":24.45}")).isNull(); assertThat(adapter.fromJson("{}")).isNull(); }