@Override public JsonAdapter<?> create(Type requestedType, Set<? extends Annotation> annotations, Moshi moshi) { if (Types.equals(type, requestedType)) { JsonAdapter<T> delegate = moshi.nextAdapter(this, type, annotations); return new DefaultOnDataMismatchAdapter<>(delegate, defaultValue); } return null; } };
private JsonAdapter.Factory newFruitFactory() { return DefaultOnDataMismatchAdapter.newFactory(Fruit.class, null); }
@Test public void factorySupportsType() throws Exception { Type parameterized = Types.newParameterizedType(List.class, String.class); List<String> fallback = Collections.singletonList("test"); // Build a moshi instance using the adapter under test and one that will throw on each read. Moshi moshi = buildMoshi(DefaultOnDataMismatchAdapter.newFactory(parameterized, fallback)) .newBuilder() .add(new JsonAdapter.Factory() { @Override public JsonAdapter<?> create(Type type, Set<? extends Annotation> annotations, Moshi moshi) { final JsonAdapter<Object> next = moshi.nextAdapter(this, type, annotations); return new JsonAdapter<Object>() { @Override public Object fromJson(JsonReader reader) throws IOException { throw new JsonDataException("Fail for all types"); } @Override public void toJson(JsonWriter writer, Object value) throws IOException { next.toJson(writer, value); } }; } }) .build(); JsonAdapter<List<String>> adapter = moshi.adapter(parameterized); List<String> fromJson = adapter.fromJson("[]"); assertThat(fromJson) .isEqualTo(fallback) .containsExactly("test"); String toJson = adapter.toJson(fromJson); assertThat(toJson).isEqualTo("[\"test\"]"); }