BirthDateJsonAdapter extends JsonAdapter<SafeCalendar> { @Override public SafeCalendar fromJson(JsonReader reader) throws IOException { SafeCalendar calendar = new SafeCalendar(); reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (reader.peek() == Token.NULL) { reader.skipValue(); continue; } if ("year".equals(name)) { calendar.set(Calendar.YEAR, reader.nextInt()); } else if ("month".equals(name)) { calendar.set(Calendar.MONTH, reader.nextInt() - 1); } else if ("day".equals(name)) { calendar.set(Calendar.DAY_OF_MONTH, reader.nextInt()); } else { throw new IOException("birthday should contain 'year', 'month' and/or 'day', found $" + name); } } reader.endObject(); return calendar; } BirthDateJsonAdapter(); @Override SafeCalendar fromJson(JsonReader reader); @Override void toJson(JsonWriter writer, SafeCalendar value); static final JsonAdapter.Factory FACTORY; }
@Test public void failsOnInvalidBirthday() throws Exception { try { validBirthdayAdapter().fromJson("{\n" + " \"day\": 1,\n" + " \"nope\": 3\n" + '}'); } catch (IOException ex) { assertThat(ex.getMessage()).isEqualTo("birthday should contain 'year', 'month' and/or 'day', found $nope"); } }
@Test public void nullBirthDay() throws Exception { SafeCalendar fromJson = validBirthdayAdapter().fromJson("{\n" + " \"year\":null,\n" + " \"month\":null,\n" + " \"day\":null\n" + '}'); assertThat(fromJson.isSet(Calendar.YEAR)).isFalse(); assertThat(fromJson.isSet(Calendar.MONTH)).isFalse(); assertThat(fromJson.isSet(Calendar.DAY_OF_MONTH)).isFalse(); }