GeoCodeJsonAdapter extends JsonAdapter<GeoCode> { @Override public GeoCode fromJson(JsonReader reader) throws IOException { Double latitude = null; Double longitude = null; int accuracy = 0; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (reader.peek() == Token.NULL) { reader.skipValue(); continue; } if ("accuracy" .equals(name)) { accuracy = reader.nextInt(); } else if ("latitude" .equals(name)) { latitude = reader.nextDouble(); } else if ("longitude" .equals(name)) { longitude = reader.nextDouble(); } else { reader.skipValue(); } } reader.endObject(); if (latitude == null || longitude == null) return null; return new GeoCode(accuracy, latitude, longitude); } GeoCodeJsonAdapter(); @Override GeoCode fromJson(JsonReader reader); @Override void toJson(JsonWriter writer, GeoCode geoCode); @Override String toString(); static final JsonAdapter.Factory FACTORY; }
@Test public void ignoresInvalidGeoCode() throws Exception { JsonAdapter<GeoCode> adapter = geoCodeAdapter(GeoCode.class); assertThat(adapter.fromJson("{\"accuracy\":12,\"latitude\":null,\"longitude\":null}")).isNull(); assertThat(adapter.fromJson("{\"latitude\":34.2,\"longitude\":null}")).isNull(); assertThat(adapter.fromJson("{\"latitude\":null,\"longitude\":24.45}")).isNull(); assertThat(adapter.fromJson("{\"unknown\":null,\"longitude\":24.45}")).isNull(); assertThat(adapter.fromJson("{}")).isNull(); }