All Projects β†’ serj-lotutovici β†’ Moshi Lazy Adapters

serj-lotutovici / Moshi Lazy Adapters

Licence: apache-2.0
A collection of simple JsonAdapters for Moshi.

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to Moshi Lazy Adapters

Boltons
πŸ”© Like builtins, but boltons. 250+ constructs, recipes, and snippets which extend (and rely on nothing but) the Python standard library. Nothing like Michael Bolton.
Stars: ✭ 5,671 (+3489.24%)
Mutual labels:  json, utilities
Flatjson
A fast JSON parser (and builder)
Stars: ✭ 39 (-75.32%)
Mutual labels:  json, utilities
Utils
πŸ›  Lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.
Stars: ✭ 1,158 (+632.91%)
Mutual labels:  json, utilities
I18next Gettext Converter
converts gettext .mo or .po to 18next json format and vice versa
Stars: ✭ 150 (-5.06%)
Mutual labels:  json
Logstash Logback Encoder
Logback JSON encoder and appenders
Stars: ✭ 1,987 (+1157.59%)
Mutual labels:  json
Node Jsonpointer
JSON Pointer (RFC6901) implementation for Node.js
Stars: ✭ 155 (-1.9%)
Mutual labels:  json
Ifvisible.js
Crossbrowser & lightweight way to check if user is looking at the page or interacting with it.
Stars: ✭ 1,896 (+1100%)
Mutual labels:  utilities
Json Splora
GUI for editing, visualizing, and manipulating JSON data
Stars: ✭ 1,818 (+1050.63%)
Mutual labels:  json
Helios
A purely functional JSON library for Kotlin built on Ξ›rrow
Stars: ✭ 157 (-0.63%)
Mutual labels:  json
Rbbjson
Flexible JSON traversal for rapid prototyping.
Stars: ✭ 155 (-1.9%)
Mutual labels:  json
Swissarmylib
Collection of helpful utilities we use in our Unity projects.
Stars: ✭ 154 (-2.53%)
Mutual labels:  utilities
World Cup.json
Free open public domain football data for the world cups in JSON incl. Russia 2018 and more - No API key required ;-)
Stars: ✭ 152 (-3.8%)
Mutual labels:  json
Orjson
Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy
Stars: ✭ 2,595 (+1542.41%)
Mutual labels:  json
Gelatin
Transform text files to XML, JSON, or YAML
Stars: ✭ 150 (-5.06%)
Mutual labels:  json
Restinstance
Robot Framework library for RESTful JSON APIs
Stars: ✭ 157 (-0.63%)
Mutual labels:  json
Jose2go
Golang (GO) implementation of Javascript Object Signing and Encryption specification
Stars: ✭ 150 (-5.06%)
Mutual labels:  json
Browser Extension Json Discovery
Browser (Chrome, Firefox) extension for JSON discovery
Stars: ✭ 157 (-0.63%)
Mutual labels:  json
Poison
An incredibly fast, pure Elixir JSON library
Stars: ✭ 1,898 (+1101.27%)
Mutual labels:  json
Awscloudformation Samples
Sample AWS CloudFormation templates
Stars: ✭ 153 (-3.16%)
Mutual labels:  json
Dhallj
Dhall for Java
Stars: ✭ 154 (-2.53%)
Mutual labels:  json

Moshi Lazy Adapters

Build Status codecov Latest Build Android Arsenal

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.
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].