/** * Adds a moshi instance to build on <b>top</b>. * <p> * <b>DISCLAIMER: </b> This will extract all custom adapter factories declared in the provided instance * and create a builder to which internal declared factories will be added. Keep in mind that for {@linkplain * Moshi} the order of custom factories maters and the resulting object will favor factories from the * provided {@linkplain Moshi moshi}, which can brake expected behaviour. This means that by adding your own * {@link Moshi} you may override adapters declared internally by {@link XingApi}, but you should do that at * your own risk. * <p> * <b>NOTE: </b>This method can be called only once, otherwise an exception will be thrown. * * @throws java.lang.IllegalStateException If the internal builder was already initialized. */ public final T moshi(Moshi moshi) { stateNull(moshiBuilder, "Only one instance of Moshi is allowed"); moshiBuilder = checkNotNull(moshi, "moshi == null").newBuilder(); return self(); }
@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\"]"); }