Moshi Lazy Adapters

Additional

Language
Java
Version
1.2 (Nov 8, 2016)
Created
Jul 14, 2016
Updated
May 2, 2018
Owner
Serj Lotutovici (serj-lotutovici)
Contributors
Serj Lotutovici (serj-lotutovici)
Niklas Baudy (Vacation) (vanniktech)
John Carlson (Jawnnypoo)
Eric Cochran (NightlyNexus)
Yahya Bayramoğlu (yayaa)
adauvalter
6
Activity
Badge
Generate
Download
Source code

Advertisement

Moshi Lazy Adapters

A collection of simple JsonAdapters for Moshi.

This library acts as an extension to Moshi by providing general purpose, yet useful JsonAdapters that are not present in the main library. Most provided adapters are linked via specialized JsonQualifier annotations that alter serialization/deserialization strategies.

How To Use It

This library is not forcing any of it's own adapters by default. To leverage from any of the provided annotations/adapters add their respective factory to your Moshi.Builder:

// Creates a Moshi instance with an adapter that will handle the @Wrapped annotations.
Moshi moshi = new Moshi.Builder()
  .add(Wrapped.ADAPTER_FACTORY)
  .build();
Overall contract

Every declared annotation/adapter in this library (unless specified in the class's documentation) supports adapter composition. Which means that no JsonAdapter.Factory will short circuit adapter construction on it's own annotation, and instead will delegate to the next adapter returned by Moshi. Meaning that given the following type declaration:

interface WebService {
  @GET("/data")
  @Wrapped(path={"result", "data"}) @FirstElement MyData getData();
}

The resulting JsonAdapter will unwrap a list of MyData from the json response and return only the first element of that list.

One important concept to keep in mind, that the order of declared annotations in the example above does not have any influence on the way how the final adapter will be constructed. Instead the order of the JsonAdapter.Factory's added to the Moshi instance is what plays a major role in overall behavior. Meaning that in order for the example above to satisfy the expected result, one must add the factories in the following order:

Moshi moshi = new Moshi.Builder()
  .add(Wrapped.ADAPTER_FACTORY)
  .add(FirstElement.ADAPTER_FACTORY)
  .build()

Some Lazy Adapters

@Wrapped

Some apis enjoy wrapping the response object inside other json objects. This creates a lot of inconvenience when it comes to consuming the request. The following example contains a list of a users favorite pokemon which is wrapped behind two keys:

{
  "favorite_pokemon": {
    "pokemons": [
      "Snorlax",
      "Pikachu",
      "Bulbasaur",
      "Charmander",
      "Squirtle"
    ]
  }
}

In the end the consumer is just interested in the names of the pokemon, but the json object forces to create a wrapping object, which will contain the list:

class FavoritePokemonResponse {
  FavoritePokemon favorite_pokemon;
}

class FavoritePokemon {
  List<String> pokemons;
}

A custom adapter would be another option, and WrappedJsonAdapter is just the one. By annotating the response type with @Wrapped and providing the path to the desired list, the need for an additional object is dropped:

// This assumes that Retrofit is used to obtain the response.
interface PokemonService {
  @GET("/pokemon/favorite")
  @Wrapped({"favorite_pokemon", "pokemons"}) Call<List<String>> getFavorite();
}

No need for a new class, which results in less code and less methods generated by the consumer code. You can also annotate any field in your response entity and the same rules will apply.

@FallbackOnNull

Primitives are simple and safe. Primitives have also a smaller memory footprint. Some apis may return null for values that are normally processed as primitives. A safe alternative would be to use their boxed counterparts, but that would result in redundant boxing and unboxing. By annotating any primitive field with @FallbackOnNull the consumer can specify a default value for the field, in case it's json representation is null.

[
  {
    "name": "Pikachu",
    "number_of_wins": 1
  },
  {
    "name": "Magikarp",
    "number_of_wins": null
  } 
]

The json above contains a list of pokemon of a user with their names and the number of wins the respective pokemon has obtained during it's trainings of fights. Notice that the 'Magikarp' pokemon has null wins. Normally the representing POJO would declare the filed as Integer, but #perfmatters. With @FallbackOnNull the Pokemon object can be declared as:

class Pokemon {
  String name;
  @FallbackOnNull int number_of_wins;
}

If the incoming value would be null the number_of_wins field would default to Integer.MIN_VALUE, this can be altered by providing an alternative fallback:

  @FallbackOnNull(fallbackInt = -1) int number_of_wins;

See FallbackOnNull's documentation for a full reference.

List of provided Adapters

  • DefaultOnDataMismatchAdapter - Allows the consumer to provided a default fallback value for any type.
  • SerializeNulls (annotation) - Serializes a value even if it's null;
  • FirstElement (annotation) - Deserializes only the first element of a list.
  • LastElement (annotation) - Deserializes only the last element of a list.
  • ElementAt (annotation) - Deserializes an element from a specified position of a list.
  • FallbackOnNull (annotation) - Fallbacks to a default value in case the json field is null.
  • FallbackEnum (annotation) - Fallbacks to a default enum value if the parsed value can not be matched to an existing one.
  • Wrapped (annotation) - Unwraps a json object under the specified path when parsing, and wraps it when serializing to json.
  • SerializeOnly (annotation) - Only serializes the annotated field, and ignores it during deserialization.
  • DeserializeOnly (annotation) - Only deserializes the annotated field, and ignores it during serialization.
  • Transient (annotation) - (Targets methods only) indicates that a field should be ignored for serialization/deserialization.
  • SerializeOnlyNonEmpty (annotation) - Will serialize a collection or array only if it contains at-least one value.

Download

Download the latest JAR or depend via Maven:

<dependency>
  <groupId>com.serjltt.moshi</groupId>
  <artifactId>moshi-lazy-adapters</artifactId>
  <version>x.y</version>
</dependency>

or Gradle:

compile 'com.serjltt.moshi:moshi-lazy-adapters:x.y'

Snapshots of the development version are available in Sonatype's snapshots repository.

License

Copyright 2017 Serj Lotutovici

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.