Moshi Lazy Adapters


Source link: https://github.com/serj-lotutovici/moshi-lazy-adapters

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. 

Resources

SerializableParcelableGeneratorPlugin for IntelliJ IDEA & Android Studio to generator SerializableParcelable code.

MaterialDialogBottomSheet is a custom dialog implementation to use BottomSheet MaterialView feature of Lollipop in older versions

Pulls notifications from a remote JSON file and shows them in your app.

Android progress bar with cool animation.

A demo usage of Fresco to show how to load images.

Aeromock is an application server that generates HTML from template files and data files. It enables speedy frontend development without the need for server side modules. Aeromock is referred to as a lightweight mock web application server.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes