com.squareup.moshi.Types Java Examples

The following examples show how to use com.squareup.moshi.Types. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Util.java    From moshi with Apache License 2.0 6 votes vote down vote up
public ParameterizedTypeImpl(@Nullable Type ownerType, Type rawType, Type... typeArguments) {
  // Require an owner type if the raw type needs it.
  if (rawType instanceof Class<?>) {
    Class<?> enclosingClass = ((Class<?>) rawType).getEnclosingClass();
    if (ownerType != null) {
      if (enclosingClass == null || Types.getRawType(ownerType) != enclosingClass) {
        throw new IllegalArgumentException(
            "unexpected owner type for " + rawType + ": " + ownerType);
      }
    } else if (enclosingClass != null) {
      throw new IllegalArgumentException(
          "unexpected owner type for " + rawType + ": null");
    }
  }

  this.ownerType = ownerType == null ? null : canonicalize(ownerType);
  this.rawType = canonicalize(rawType);
  this.typeArguments = typeArguments.clone();
  for (int t = 0; t < this.typeArguments.length; t++) {
    if (this.typeArguments[t] == null) throw new NullPointerException();
    checkNotPrimitive(this.typeArguments[t]);
    this.typeArguments[t] = canonicalize(this.typeArguments[t]);
  }
}
 
Example #2
Source File: PolymorphicJsonAdapterFactory.java    From moshi with Apache License 2.0 6 votes vote down vote up
@Override
public JsonAdapter<?> create(Type type, Set<? extends Annotation> annotations, Moshi moshi) {
  if (Types.getRawType(type) != baseType || !annotations.isEmpty()) {
    return null;
  }

  List<JsonAdapter<Object>> jsonAdapters = new ArrayList<>(subtypes.size());
  for (int i = 0, size = subtypes.size(); i < size; i++) {
    jsonAdapters.add(moshi.adapter(subtypes.get(i)));
  }

  return new PolymorphicJsonAdapter(labelKey,
      labels,
      subtypes,
      jsonAdapters,
      defaultValue,
      defaultValueSet
  ).nullSafe();
}
 
Example #3
Source File: JsonApiConverterFactory.java    From moshi-jsonapi with MIT License 6 votes vote down vote up
private JsonAdapter<?> getAdapterFromType(Type type) {
    Class<?> rawType = Types.getRawType(type);
    JsonAdapter<?> adapter;
    if (rawType.isArray() && ResourceIdentifier.class.isAssignableFrom(rawType.getComponentType())) {
        adapter = moshi.adapter(Types.newParameterizedType(Document.class, rawType.getComponentType()));
    } else if (List.class.isAssignableFrom(rawType) && type instanceof ParameterizedType) {
        Type typeParameter = ((ParameterizedType) type).getActualTypeArguments()[0];
        if (typeParameter instanceof Class<?> && ResourceIdentifier.class.isAssignableFrom((Class<?>) typeParameter)) {
            adapter = moshi.adapter(Types.newParameterizedType(Document.class, typeParameter));
        } else {
            return null;
        }
    } else if (ResourceIdentifier.class.isAssignableFrom(rawType)) {
        adapter = moshi.adapter(Types.newParameterizedType(Document.class, rawType));
    } else if (Document.class.isAssignableFrom(rawType)) {
        adapter = moshi.adapter(Types.newParameterizedType(Document.class, Resource.class));
    } else {
        return null;
    }
    return adapter;
}
 
Example #4
Source File: ReadJsonList.java    From moshi with Apache License 2.0 6 votes vote down vote up
public void run() throws Exception {
  String json = ""
      + "[\n"
      + "  {\n"
      + "    \"rank\": \"4\",\n"
      + "    \"suit\": \"CLUBS\"\n"
      + "  },\n"
      + "  {\n"
      + "    \"rank\": \"A\",\n"
      + "    \"suit\": \"HEARTS\"\n"
      + "  },\n"
      + "  {\n"
      + "    \"rank\": \"J\",\n"
      + "    \"suit\": \"SPADES\"\n"
      + "  }\n"
      + "]";

  Moshi moshi = new Moshi.Builder().build();

  Type listOfCardsType = Types.newParameterizedType(List.class, Card.class);
  JsonAdapter<List<Card>> jsonAdapter = moshi.adapter(listOfCardsType);

  List<Card> cards = jsonAdapter.fromJson(json);
  System.out.println(cards);
}
 
Example #5
Source File: DocumentTest.java    From moshi-jsonapi with MIT License 6 votes vote down vote up
public <T extends ResourceIdentifier> JsonAdapter<Document> getDocumentAdapter(Class<T> typeParameter,
                                                                               Class<? extends Resource>... knownTypes) {
    Moshi moshi;
    if (typeParameter == null) {
        return (JsonAdapter) TestUtil.moshi(knownTypes).adapter(Document.class);
    } else if (typeParameter.getAnnotation(JsonApi.class) != null) {
        Class<? extends Resource>[] types = new Class[knownTypes.length + 1];
        types[0] = (Class) typeParameter;
        for (int i = 0; i != knownTypes.length; i++) {
            types[i + 1] = knownTypes[i];
        }
        moshi = TestUtil.moshi(types);
    } else {
        moshi = TestUtil.moshi(knownTypes);
    }
    return moshi.adapter(Types.newParameterizedType(Document.class, typeParameter));
}
 
Example #6
Source File: NetworkPolling.java    From RxJavaExplained with Apache License 2.0 6 votes vote down vote up
public NetworkPolling(@NonNull File cacheFile) {
  this.cacheFile = cacheFile;
  Moshi moshi = new Moshi.Builder().build();
  jsonAdapter = moshi.adapter(Types.newParameterizedType(List.class, Kitten.class));
  kittensObservable = Observable
      .interval(0, 5, TimeUnit.SECONDS)
      // Read from cached file at first subscription
      .doOnSubscribe(this::readKittensFromCache)
      // For each interval, call our service
      .flatMap(interval -> KittensApi.getAllKittens())
      // Return the cached data instead of empty response
      .map(kittens -> kittens == null || kittens.size() == 0 ?
          cachedKittens : kittens)
      // Update our cache
      .doOnNext(this::writeKittensToCache)
      // Return the cached version on error
      .onErrorReturn(throwable -> cachedKittens)
      // Multicasts the data from the original to all subscribers. Alias for publish().refCount()
      .share()
      // Start with the cached data
      .startWith(cachedKittens)
  ;
}
 
Example #7
Source File: DefaultOnDataMismatchAdapter.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
/** Builds an adapter that fallbacks to a default value in case there's a mismatch. */
public static <T> JsonAdapter.Factory newFactory(final Type type, final T defaultValue) {
  return new Factory() {
    @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;
    }
  };
}
 
Example #8
Source File: ArrayUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeserializingJsonArray_thenListProduced() throws IOException {
    Moshi moshi = new Moshi.Builder()
      .build();
    Type type = Types.newParameterizedType(List.class, String.class);
    JsonAdapter<List<String>> jsonAdapter = moshi.adapter(type);

    String json = "[\"One\",\"Two\",\"Three\"]";
    List<String> result = jsonAdapter.fromJson(json);
    System.out.println(result);
}
 
Example #9
Source File: ArrayUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSerializingList_thenJsonArrayProduced() {
    Moshi moshi = new Moshi.Builder()
      .build();
    Type type = Types.newParameterizedType(List.class, String.class);
    JsonAdapter<List<String>> jsonAdapter = moshi.adapter(type);

    String json = jsonAdapter.toJson(Arrays.asList("One", "Two", "Three"));
    System.out.println(json);
}
 
Example #10
Source File: Unwrap.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Override public @Nullable JsonAdapter<?> create(
    Type type, Set<? extends Annotation> annotations, Moshi moshi) {
  Set<? extends Annotation> delegateAnnotations =
      Types.nextAnnotations(annotations, Enveloped.class);
  if (delegateAnnotations == null) {
    return null;
  }
  Type envelope =
      Types.newParameterizedTypeWithOwner(EnvelopeJsonAdapter.class, Envelope.class, type);
  JsonAdapter<Envelope<?>> delegate = moshi.nextAdapter(this, envelope, delegateAnnotations);
  return new EnvelopeJsonAdapter(delegate);
}
 
Example #11
Source File: CustomAdapterFactory.java    From moshi with Apache License 2.0 5 votes vote down vote up
public void run() throws Exception {
  Moshi moshi = new Moshi.Builder()
      .add(new SortedSetAdapterFactory())
      .build();
  JsonAdapter<SortedSet<String>> jsonAdapter = moshi.adapter(
      Types.newParameterizedType(SortedSet.class, String.class));

  TreeSet<String> model = new TreeSet<>();
  model.add("a");
  model.add("b");
  model.add("c");

  String json = jsonAdapter.toJson(model);
  System.out.println(json);
}
 
Example #12
Source File: RecoverFromTypeMismatch.java    From moshi with Apache License 2.0 5 votes vote down vote up
public void run() throws Exception {
  String json = "[\"DIAMONDS\", \"STARS\", \"HEARTS\"]";

  Moshi moshi = new Moshi.Builder()
      .add(DefaultOnDataMismatchAdapter.newFactory(Suit.class, Suit.CLUBS))
      .build();
  JsonAdapter<List<Suit>> jsonAdapter = moshi.adapter(
      Types.newParameterizedType(List.class, Suit.class));

  List<Suit> suits = jsonAdapter.fromJson(json);
  System.out.println(suits);
}
 
Example #13
Source File: ModelListAdapterTest.java    From android with Apache License 2.0 5 votes vote down vote up
@Test public void testModelListAdapter() throws IOException {
  Buffer buffer = new Buffer();
  JsonWriter jsonWriter = JsonWriter.of(buffer);
  JsonAdapter<List<Nation>> adapter =
      moshi.adapter(Types.newParameterizedType(List.class, Nation.class));
  Nation nation = Nation.create(1, 1, "foo", "bar", "baz");
  List<Nation> nations = Collections.singletonList(nation);
  adapter.toJson(jsonWriter, nations);
  String json = buffer.readUtf8();
  buffer = new Buffer().writeUtf8(json);
  JsonReader jsonReader = JsonReader.of(buffer);
  assertThat(adapter.fromJson(jsonReader)).isEqualTo(nations);
}
 
Example #14
Source File: ModelListAdapterFactory.java    From android with Apache License 2.0 5 votes vote down vote up
@Override
public JsonAdapter<?> create(Type type, Set<? extends Annotation> annotations, Moshi moshi) {
  if (type.equals(Types.newParameterizedType(List.class, this.type))) {
    return new ModelListAdapter<>(this.type, moshi);
  } else {
    return null;
  }
}
 
Example #15
Source File: MoshiMessageBodyWriterTest.java    From jax-rs-moshi with Apache License 2.0 5 votes vote down vote up
@Test public void writesParameterized() throws IOException {
  Buffer data = new Buffer();
  MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
  Type genericType = Types.newParameterizedType(List.class, String.class);
  writer.writeTo(singletonList("hey"), List.class, genericType, new Annotation[0],
      APPLICATION_JSON_TYPE, headers, data.outputStream());
  assertEquals("[\"hey\"]", data.readUtf8());
  assertTrue(headers.isEmpty());
}
 
Example #16
Source File: WrappedJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void arrayOfObjects() throws Exception {
  JsonAdapter<List<Data2>> adapter = moshi.adapter(
      Types.newParameterizedType(List.class, Data2.class));

  List<Data2> fromJson = adapter.fromJson("[\n"
      + "  {\n"
      + "    \"data\": {\n"
      + "      \"1\": {\n"
      + "        \"2\": {\n"
      + "          \"str\": \"funny\",\n"
      + "          \"val\": 42\n"
      + "        }\n"
      + "      }\n"
      + "    }\n"
      + "  },\n"
      + "  {\n"
      + "    \"data\": {\n"
      + "      \"1\": {\n"
      + "        \"2\": {\n"
      + "          \"str\": \"prime\",\n"
      + "          \"val\": 43\n"
      + "        }\n"
      + "      }\n"
      + "    }\n"
      + "  }\n"
      + "]");
  assertThat(fromJson.get(0).data.str).isEqualTo("funny");
  assertThat(fromJson.get(0).data.val).isEqualTo(42);
  assertThat(fromJson.get(1).data.str).isEqualTo("prime");
  assertThat(fromJson.get(1).data.val).isEqualTo(43);

  String toJson = adapter.toJson(fromJson);
  assertThat(toJson).isEqualTo("["
      + "{\"data\":{\"1\":{\"2\":{\"str\":\"funny\",\"val\":42}}}},"
      + "{\"data\":{\"1\":{\"2\":{\"str\":\"prime\",\"val\":43}}}}"
      + "]");
}
 
Example #17
Source File: FilterNullsJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void nullList() throws Exception {
  JsonAdapter<List<String>> adapter = moshi.adapter(Types.newParameterizedType(List.class,
      String.class), FilterNulls.class);

  List<String> fromJson = adapter.fromJson("null");
  assertThat(fromJson).isNull();

  String toJson = adapter.toJson(null);
  assertThat(toJson).isEqualTo("null");
}
 
Example #18
Source File: MoshiMessageBodyReaderTest.java    From jax-rs-moshi with Apache License 2.0 5 votes vote down vote up
@Test public void readsParameterized() throws IOException {
  Buffer data = new Buffer().writeUtf8("[\"hey\"]");
  Class<Object> type = (Class) List.class;
  Type genericType = Types.newParameterizedType(List.class, String.class);
  MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
  Object result = reader.readFrom(type, genericType, new Annotation[0], APPLICATION_JSON_TYPE,
      headers, data.inputStream());
  assertEquals(singletonList("hey"), result);
  assertTrue(headers.isEmpty());
}
 
Example #19
Source File: MoshiParamConverterFactoryTest.java    From jax-rs-moshi with Apache License 2.0 5 votes vote down vote up
@Test public void jsonAnnotationReturnsConverterParameterized() {
  Type genericType = Types.newParameterizedType(List.class, String.class);
  ParamConverter<List<String>> converter =
      (ParamConverter) provider.getConverter(List.class, genericType, new Annotation[] {
          Annotations.real()
      });
  List<String> value = converter.fromString("[\"hey\"]");
  assertEquals(singletonList("hey"), value);
  String json = converter.toString(singletonList("hey"));
  assertEquals("[\"hey\"]", json);
}
 
Example #20
Source File: DocumentTest.java    From moshi-jsonapi with MIT License 5 votes vote down vote up
@Test
public void deserialize_object_to_object_typed_document() throws Exception {
    Moshi moshi = TestUtil.moshi(Article.class);
    JsonAdapter<?> adapter = moshi.adapter(Types.newParameterizedType(ObjectDocument.class, Article.class));
    assertThat(adapter, instanceOf(ResourceAdapterFactory.DocumentAdapter.class));
    ObjectDocument<Article> objectDocument = ((ObjectDocument<Article>) adapter.fromJson(TestUtil.fromResource("/single.json")));
    assertThat(objectDocument, instanceOf(ObjectDocument.class));
    assertOnArticle1(objectDocument.<Article>asObjectDocument().get());
}
 
Example #21
Source File: DocumentTest.java    From moshi-jsonapi with MIT License 5 votes vote down vote up
@Test
public void deserialize_array_to_array_typed_document() throws Exception {
    Moshi moshi = TestUtil.moshi(Article.class);
    JsonAdapter<?> adapter = moshi.adapter(Types.newParameterizedType(ArrayDocument.class, Article.class));
    assertThat(adapter, instanceOf(ResourceAdapterFactory.DocumentAdapter.class));
    ArrayDocument<Article> arrayDocument = ((ArrayDocument<Article>) adapter.fromJson(TestUtil.fromResource("/multiple_compound.json")));
    assertThat(arrayDocument.size(), equalTo(1));
    assertOnArticle1(arrayDocument.get(0));
}
 
Example #22
Source File: FilterNullsJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void noNullValues() throws Exception {
  JsonAdapter<List<String>> adapter = moshi.adapter(Types.newParameterizedType(List.class,
      String.class), FilterNulls.class);

  List<String> fromJson = adapter.fromJson("[\"apple\",\"banana\"]");
  assertThat(fromJson).containsExactly("apple", "banana");

  String toJson = adapter.toJson(fromJson);
  assertThat(toJson).isEqualTo("[\"apple\",\"banana\"]");
}
 
Example #23
Source File: FilterNullsJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void nullValues() throws Exception {
  JsonAdapter<List<String>> adapter = moshi.adapter(Types.newParameterizedType(List.class,
      String.class), FilterNulls.class);

  List<String> fromJson = adapter.fromJson("[\"apple\",\"banana\",null]");
  assertThat(fromJson).containsExactly("apple", "banana");

  String toJson = adapter.toJson(new ArrayList<>(asList("apple", "banana", null)));
  assertThat(toJson).isEqualTo("[\"apple\",\"banana\"]");
}
 
Example #24
Source File: FilterNullsJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void toStringReflectsInnerAdapter() throws Exception {
  JsonAdapter<String> adapter = moshi.adapter(Types.newParameterizedType(Collection.class,
      String.class), FilterNulls.class);

  assertThat(adapter.toString())
      .isEqualTo("JsonAdapter(String).nullSafe().collection().nullSafe().filterNulls()");
}
 
Example #25
Source File: MoshiSpeaker.java    From Jolyglot with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override public ParameterizedType newParameterizedType(Type rawType,
    Type... typeArguments) {
  return Types.newParameterizedType(rawType, typeArguments);
}
 
Example #26
Source File: MoshiSpeaker.java    From Jolyglot with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override public GenericArrayType arrayOf(Type componentType) {
  return Types.arrayOf(componentType);
}
 
Example #27
Source File: LastElementJsonAdapter.java    From moshi-lazy-adapters with Apache License 2.0 4 votes vote down vote up
LastElementJsonAdapter(Type type, Moshi moshi) {
  Type listType = Types.newParameterizedType(List.class, type);
  delegate = moshi.adapter(listType);
}
 
Example #28
Source File: DocumentTest.java    From moshi-jsonapi with MIT License 4 votes vote down vote up
@Test(expected = JsonDataException.class)
public void deserialize_multiple_polymorphic_no_default() throws Exception {
    TestUtil.moshi(true, Article.class)
            .adapter(Types.newParameterizedType(Document.class, Resource.class))
            .fromJson(TestUtil.fromResource("/multiple_polymorphic.json"));
}
 
Example #29
Source File: DocumentTest.java    From moshi-jsonapi with MIT License 4 votes vote down vote up
@Test(expected = JsonDataException.class)
public void deserialize_no_default() throws Exception {
    TestUtil.moshi(true, Article.class)
            .adapter(Types.newParameterizedType(Document.class, Article.class))
            .fromJson(TestUtil.fromResource("/multiple_compound.json"));
}
 
Example #30
Source File: JsonApiConverterFactory.java    From moshi-jsonapi with MIT License 4 votes vote down vote up
MoshiRequestBodyConverter(JsonAdapter<Document> adapter, Type type) {
    this.adapter = adapter;
    this.rawType = (Class<T>) Types.getRawType(type);
}