• Stars
    star
    9,756
  • Rank 3,623 (Top 0.08 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created over 10 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A modern JSON library for Kotlin and Java.

Moshi

Moshi is a modern JSON library for Android, Java and Kotlin. It makes it easy to parse JSON into Java and Kotlin classes:

Note: The Kotlin examples of this README assume use of either Kotlin code gen or KotlinJsonAdapterFactory for reflection. Plain Java-based reflection is unsupported on Kotlin classes.

Java
String json = ...;

Moshi moshi = new Moshi.Builder().build();
JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class);

BlackjackHand blackjackHand = jsonAdapter.fromJson(json);
System.out.println(blackjackHand);
Kotlin
val json: String = ...

val moshi: Moshi = Moshi.Builder().build()
val jsonAdapter: JsonAdapter<BlackjackHand> = moshi.adapter<BlackjackHand>()

val blackjackHand = jsonAdapter.fromJson(json)
println(blackjackHand)

And it can just as easily serialize Java or Kotlin objects as JSON:

Java
BlackjackHand blackjackHand = new BlackjackHand(
    new Card('6', SPADES),
    Arrays.asList(new Card('4', CLUBS), new Card('A', HEARTS)));

Moshi moshi = new Moshi.Builder().build();
JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class);

String json = jsonAdapter.toJson(blackjackHand);
System.out.println(json);
Kotlin
val blackjackHand = BlackjackHand(
    Card('6', SPADES),
    listOf(Card('4', CLUBS), Card('A', HEARTS))
  )

val moshi: Moshi = Moshi.Builder().build()
val jsonAdapter: JsonAdapter<BlackjackHand> = moshi.adapter<BlackjackHand>()

val json: String = jsonAdapter.toJson(blackjackHand)
println(json)

Built-in Type Adapters

Moshi has built-in support for reading and writing Java’s core data types:

  • Primitives (int, float, char...) and their boxed counterparts (Integer, Float, Character...).
  • Arrays, Collections, Lists, Sets, and Maps
  • Strings
  • Enums

It supports your model classes by writing them out field-by-field. In the example above Moshi uses these classes:

Java
class BlackjackHand {
  public final Card hidden_card;
  public final List<Card> visible_cards;
  ...
}

class Card {
  public final char rank;
  public final Suit suit;
  ...
}

enum Suit {
  CLUBS, DIAMONDS, HEARTS, SPADES;
}
Kotlin
class BlackjackHand(
  val hidden_card: Card,
  val visible_cards: List<Card>,
  ...
)

class Card(
  val rank: Char,
  val suit: Suit
  ...
)

enum class Suit {
  CLUBS, DIAMONDS, HEARTS, SPADES;
}

to read and write this JSON:

{
  "hidden_card": {
    "rank": "6",
    "suit": "SPADES"
  },
  "visible_cards": [
    {
      "rank": "4",
      "suit": "CLUBS"
    },
    {
      "rank": "A",
      "suit": "HEARTS"
    }
  ]
}

The Javadoc catalogs the complete Moshi API, which we explore below.

Custom Type Adapters

With Moshi, it’s particularly easy to customize how values are converted to and from JSON. A type adapter is any class that has methods annotated @ToJson and @FromJson.

For example, Moshi’s default encoding of a playing card is verbose: the JSON defines the rank and suit in separate fields: {"rank":"A","suit":"HEARTS"}. With a type adapter, we can change the encoding to something more compact: "4H" for the four of hearts or "JD" for the jack of diamonds:

Java
class CardAdapter {
  @ToJson String toJson(Card card) {
    return card.rank + card.suit.name().substring(0, 1);
  }

  @FromJson Card fromJson(String card) {
    if (card.length() != 2) throw new JsonDataException("Unknown card: " + card);

    char rank = card.charAt(0);
    switch (card.charAt(1)) {
      case 'C': return new Card(rank, Suit.CLUBS);
      case 'D': return new Card(rank, Suit.DIAMONDS);
      case 'H': return new Card(rank, Suit.HEARTS);
      case 'S': return new Card(rank, Suit.SPADES);
      default: throw new JsonDataException("unknown suit: " + card);
    }
  }
}
Kotlin
class CardAdapter {
  @ToJson fun toJson(card: Card): String {
    return card.rank + card.suit.name.substring(0, 1)
  }

  @FromJson fun fromJson(card: String): Card {
    if (card.length != 2) throw JsonDataException("Unknown card: $card")

    val rank = card[0]
    return when (card[1]) {
      'C' -> Card(rank, Suit.CLUBS)
      'D' -> Card(rank, Suit.DIAMONDS)
      'H' -> Card(rank, Suit.HEARTS)
      'S' -> Card(rank, Suit.SPADES)
      else -> throw JsonDataException("unknown suit: $card")
    }
  }
}

Register the type adapter with the Moshi.Builder and we’re good to go.

Java
Moshi moshi = new Moshi.Builder()
    .add(new CardAdapter())
    .build();
Kotlin
val moshi = Moshi.Builder()
    .add(CardAdapter())
    .build()

VoilΓ :

{
  "hidden_card": "6S",
  "visible_cards": [
    "4C",
    "AH"
  ]
}

Another example

Note that the method annotated with @FromJson does not need to take a String as an argument. Rather it can take input of any type and Moshi will first parse the JSON to an object of that type and then use the @FromJson method to produce the desired final value. Conversely, the method annotated with @ToJson does not have to produce a String.

Assume, for example, that we have to parse a JSON in which the date and time of an event are represented as two separate strings.

{
  "title": "Blackjack tournament",
  "begin_date": "20151010",
  "begin_time": "17:04"
}

We would like to combine these two fields into one string to facilitate the date parsing at a later point. Also, we would like to have all variable names in CamelCase. Therefore, the Event class we want Moshi to produce like this:

Java
class Event {
  String title;
  String beginDateAndTime;
}
Kotlin
class Event(
  val title: String,
  val beginDateAndTime: String
)

Instead of manually parsing the JSON line per line (which we could also do) we can have Moshi do the transformation automatically. We simply define another class EventJson that directly corresponds to the JSON structure:

Java
class EventJson {
  String title;
  String begin_date;
  String begin_time;
}
Kotlin
class EventJson(
  val title: String,
  val begin_date: String,
  val begin_time: String
)

And another class with the appropriate @FromJson and @ToJson methods that are telling Moshi how to convert an EventJson to an Event and back. Now, whenever we are asking Moshi to parse a JSON to an Event it will first parse it to an EventJson as an intermediate step. Conversely, to serialize an Event Moshi will first create an EventJson object and then serialize that object as usual.

Java
class EventJsonAdapter {
  @FromJson Event eventFromJson(EventJson eventJson) {
    Event event = new Event();
    event.title = eventJson.title;
    event.beginDateAndTime = eventJson.begin_date + " " + eventJson.begin_time;
    return event;
  }

  @ToJson EventJson eventToJson(Event event) {
    EventJson json = new EventJson();
    json.title = event.title;
    json.begin_date = event.beginDateAndTime.substring(0, 8);
    json.begin_time = event.beginDateAndTime.substring(9, 14);
    return json;
  }
}
Kotlin
class EventJsonAdapter {
  @FromJson
  fun eventFromJson(eventJson: EventJson): Event {
    return Event(
      title = eventJson.title,
      beginDateAndTime = "${eventJson.begin_date} ${eventJson.begin_time}"
    )
  }

  @ToJson
  fun eventToJson(event: Event): EventJson {
    return EventJson(
      title = event.title,
      begin_date = event.beginDateAndTime.substring(0, 8),
      begin_time = event.beginDateAndTime.substring(9, 14),
    )
  }
}

Again we register the adapter with Moshi.

Java
Moshi moshi = new Moshi.Builder()
    .add(new EventJsonAdapter())
    .build();
Kotlin
val moshi = Moshi.Builder()
    .add(EventJsonAdapter())
    .build()

We can now use Moshi to parse the JSON directly to an Event.

Java
JsonAdapter<Event> jsonAdapter = moshi.adapter(Event.class);
Event event = jsonAdapter.fromJson(json);
Kotlin
val jsonAdapter = moshi.adapter<Event>()
val event = jsonAdapter.fromJson(json)

Adapter convenience methods

Moshi provides a number of convenience methods for JsonAdapter objects:

  • nullSafe()
  • nonNull()
  • lenient()
  • failOnUnknown()
  • indent()
  • serializeNulls()

These factory methods wrap an existing JsonAdapter into additional functionality. For example, if you have an adapter that doesn't support nullable values, you can use nullSafe() to make it null safe:

Java
String dateJson = "\"2018-11-26T11:04:19.342668Z\"";
String nullDateJson = "null";

// Hypothetical IsoDateDapter, doesn't support null by default
JsonAdapter<Date> adapter = new IsoDateDapter();

Date date = adapter.fromJson(dateJson);
System.out.println(date); // Mon Nov 26 12:04:19 CET 2018

Date nullDate = adapter.fromJson(nullDateJson);
// Exception, com.squareup.moshi.JsonDataException: Expected a string but was NULL at path $

Date nullDate = adapter.nullSafe().fromJson(nullDateJson);
System.out.println(nullDate); // null
Kotlin
val dateJson = "\"2018-11-26T11:04:19.342668Z\""
val nullDateJson = "null"

// Hypothetical IsoDateDapter, doesn't support null by default
val adapter: JsonAdapter<Date> = IsoDateDapter()

val date = adapter.fromJson(dateJson)
println(date) // Mon Nov 26 12:04:19 CET 2018

val nullDate = adapter.fromJson(nullDateJson)
// Exception, com.squareup.moshi.JsonDataException: Expected a string but was NULL at path $

val nullDate = adapter.nullSafe().fromJson(nullDateJson)
println(nullDate) // null

In contrast to nullSafe() there is nonNull() to make an adapter refuse null values. Refer to the Moshi JavaDoc for details on the various methods.

Parse JSON Arrays

Say we have a JSON string of this structure:

[
  {
    "rank": "4",
    "suit": "CLUBS"
  },
  {
    "rank": "A",
    "suit": "HEARTS"
  }
]

We can now use Moshi to parse the JSON string into a List<Card>.

Java
String cardsJsonResponse = ...;
Type type = Types.newParameterizedType(List.class, Card.class);
JsonAdapter<List<Card>> adapter = moshi.adapter(type);
List<Card> cards = adapter.fromJson(cardsJsonResponse);
Kotlin
val cardsJsonResponse: String = ...
// We can just use a reified extension!
val adapter = moshi.adapter<List<Card>>()
val cards: List<Card> = adapter.fromJson(cardsJsonResponse)

Fails Gracefully

Automatic databinding almost feels like magic. But unlike the black magic that typically accompanies reflection, Moshi is designed to help you out when things go wrong.

JsonDataException: Expected one of [CLUBS, DIAMONDS, HEARTS, SPADES] but was ANCHOR at path $.visible_cards[2].suit
  at com.squareup.moshi.JsonAdapters$11.fromJson(JsonAdapters.java:188)
  at com.squareup.moshi.JsonAdapters$11.fromJson(JsonAdapters.java:180)
  ...

Moshi always throws a standard java.io.IOException if there is an error reading the JSON document, or if it is malformed. It throws a JsonDataException if the JSON document is well-formed, but doesn’t match the expected format.

Built on Okio

Moshi uses Okio for simple and powerful I/O. It’s a fine complement to OkHttp, which can share buffer segments for maximum efficiency.

Borrows from Gson

Moshi uses the same streaming and binding mechanisms as Gson. If you’re a Gson user you’ll find Moshi works similarly. If you try Moshi and don’t love it, you can even migrate to Gson without much violence!

But the two libraries have a few important differences:

  • Moshi has fewer built-in type adapters. For example, you need to configure your own date adapter. Most binding libraries will encode whatever you throw at them. Moshi refuses to serialize platform types (java.*, javax.*, and android.*) without a user-provided type adapter. This is intended to prevent you from accidentally locking yourself to a specific JDK or Android release.
  • Moshi is less configurable. There’s no field naming strategy, versioning, instance creators, or long serialization policy. Instead of naming a field visibleCards and using a policy class to convert that to visible_cards, Moshi wants you to just name the field visible_cards as it appears in the JSON.
  • Moshi doesn’t have a JsonElement model. Instead it just uses built-in types like List and Map.
  • No HTML-safe escaping. Gson encodes = as \u003d by default so that it can be safely encoded in HTML without additional escaping. Moshi encodes it naturally (as =) and assumes that the HTML encoder – if there is one – will do its job.

Custom field names with @Json

Moshi works best when your JSON objects and Java or Kotlin classes have the same structure. But when they don't, Moshi has annotations to customize data binding.

Use @Json to specify how Java fields or Kotlin properties map to JSON names. This is necessary when the JSON name contains spaces or other characters that aren’t permitted in Java field or Kotlin property names. For example, this JSON has a field name containing a space:

{
  "username": "jesse",
  "lucky number": 32
}

With @Json its corresponding Java or Kotlin class is easy:

Java
class Player {
  String username;
  @Json(name = "lucky number") int luckyNumber;

  ...
}
Kotlin
class Player {
  val username: String
  @Json(name = "lucky number") val luckyNumber: Int

  ...
}

Because JSON field names are always defined with their Java or Kotlin fields, Moshi makes it easy to find fields when navigating between Java or Koltin and JSON.

Alternate type adapters with @JsonQualifier

Use @JsonQualifier to customize how a type is encoded for some fields without changing its encoding everywhere. This works similarly to the qualifier annotations in dependency injection tools like Dagger and Guice.

Here’s a JSON message with two integers and a color:

{
  "width": 1024,
  "height": 768,
  "color": "#ff0000"
}

By convention, Android programs also use int for colors:

Java
class Rectangle {
  int width;
  int height;
  int color;
}
Kotlin
class Rectangle(
  val width: Int,
  val height: Int,
  val color: Int
)

But if we encoded the above Java or Kotlin class as JSON, the color isn't encoded properly!

{
  "width": 1024,
  "height": 768,
  "color": 16711680
}

The fix is to define a qualifier annotation, itself annotated @JsonQualifier:

Java
@Retention(RUNTIME)
@JsonQualifier
public @interface HexColor {
}
Kotlin
@Retention(RUNTIME)
@JsonQualifier
annotation class HexColor

Next apply this @HexColor annotation to the appropriate field:

Java
class Rectangle {
  int width;
  int height;
  @HexColor int color;
}
Kotlin
class Rectangle(
  val width: Int,
  val height: Int,
  @HexColor val color: Int
)

And finally define a type adapter to handle it:

Java
/** Converts strings like #ff0000 to the corresponding color ints. */
class ColorAdapter {
  @ToJson String toJson(@HexColor int rgb) {
    return String.format("#%06x", rgb);
  }

  @FromJson @HexColor int fromJson(String rgb) {
    return Integer.parseInt(rgb.substring(1), 16);
  }
}
Kotlin
/** Converts strings like #ff0000 to the corresponding color ints.  */
class ColorAdapter {
  @ToJson fun toJson(@HexColor rgb: Int): String {
    return "#%06x".format(rgb)
  }

  @FromJson @HexColor fun fromJson(rgb: String): Int {
    return rgb.substring(1).toInt(16)
  }
}

Use @JsonQualifier when you need different JSON encodings for the same type. Most programs shouldn’t need this @JsonQualifier, but it’s very handy for those that do.

Omitting fields

Some models declare fields that shouldn’t be included in JSON. For example, suppose our blackjack hand has a total field with the sum of the cards:

Java
public final class BlackjackHand {
  private int total;

  ...
}
Kotlin
class BlackjackHand(
  private val total: Int,

  ...
)

By default, all fields are emitted when encoding JSON, and all fields are accepted when decoding JSON. Prevent a field from being included by annotating them with @Json(ignore = true).

Java
public final class BlackjackHand {
  @Json(ignore = true)
  private int total;

  ...
}
Kotlin
class BlackjackHand(...) {
  @Json(ignore = true)
  var total: Int = 0

  ...
}

These fields are omitted when writing JSON. When reading JSON, the field is skipped even if the JSON contains a value for the field. Instead, it will get a default value. In Kotlin, these fields must have a default value if they are in the primary constructor.

Note that you can also use Java’s transient keyword or Kotlin's @Transient annotation on these fields for the same effect.

Default Values & Constructors

When reading JSON that is missing a field, Moshi relies on the Java or Kotlin or Android runtime to assign the field’s value. Which value it uses depends on whether the class has a no-arguments constructor.

If the class has a no-arguments constructor, Moshi will call that constructor and whatever value it assigns will be used. For example, because this class has a no-arguments constructor the total field is initialized to -1.

Note: This section only applies to Java reflections.

public final class BlackjackHand {
  private int total = -1;
  ...

  private BlackjackHand() {
  }

  public BlackjackHand(Card hidden_card, List<Card> visible_cards) {
    ...
  }
}

If the class doesn’t have a no-arguments constructor, Moshi can’t assign the field’s default value, even if it’s specified in the field declaration. Instead, the field’s default is always 0 for numbers, false for booleans, and null for references. In this example, the default value of total is 0!

public final class BlackjackHand {
  private int total = -1;
  ...

  public BlackjackHand(Card hidden_card, List<Card> visible_cards) {
    ...
  }
}

This is surprising and is a potential source of bugs! For this reason consider defining a no-arguments constructor in classes that you use with Moshi, using @SuppressWarnings("unused") to prevent it from being inadvertently deleted later:

public final class BlackjackHand {
  private int total = -1;
  ...

  @SuppressWarnings("unused") // Moshi uses this!
  private BlackjackHand() {
  }

  public BlackjackHand(Card hidden_card, List<Card> visible_cards) {
    ...
  }
}

Composing Adapters

In some situations Moshi's default Java-to-JSON conversion isn't sufficient. You can compose adapters to build upon the standard conversion.

In this example, we turn serialize nulls, then delegate to the built-in adapter:

Java
class TournamentWithNullsAdapter {
  @ToJson void toJson(JsonWriter writer, Tournament tournament,
      JsonAdapter<Tournament> delegate) throws IOException {
    boolean wasSerializeNulls = writer.getSerializeNulls();
    writer.setSerializeNulls(true);
    try {
      delegate.toJson(writer, tournament);
    } finally {
      writer.setLenient(wasSerializeNulls);
    }
  }
}
Kotlin
class TournamentWithNullsAdapter {
  @ToJson fun toJson(writer: JsonWriter, tournament: Tournament?,
    delegate: JsonAdapter<Tournament?>) {
    val wasSerializeNulls: Boolean = writer.getSerializeNulls()
    writer.setSerializeNulls(true)
    try {
      delegate.toJson(writer, tournament)
    } finally {
      writer.setLenient(wasSerializeNulls)
    }
  }
}

When we use this to serialize a tournament, nulls are written! But nulls elsewhere in our JSON document are skipped as usual.

Moshi has a powerful composition system in its JsonAdapter.Factory interface. We can hook in to the encoding and decoding process for any type, even without knowing about the types beforehand. In this example, we customize types annotated @AlwaysSerializeNulls, which an annotation we create, not built-in to Moshi:

Java
@Target(TYPE)
@Retention(RUNTIME)
public @interface AlwaysSerializeNulls {}
Kotlin
@Target(TYPE)
@Retention(RUNTIME)
annotation class AlwaysSerializeNulls
Java
@AlwaysSerializeNulls
static class Car {
  String make;
  String model;
  String color;
}
Kotlin
@AlwaysSerializeNulls
class Car(
  val make: String?,
  val model: String?,
  val color: String?
)

Each JsonAdapter.Factory interface is invoked by Moshi when it needs to build an adapter for a user's type. The factory either returns an adapter to use, or null if it doesn't apply to the requested type. In our case we match all classes that have our annotation.

Java
static class AlwaysSerializeNullsFactory implements JsonAdapter.Factory {
  @Override public JsonAdapter<?> create(
      Type type, Set<? extends Annotation> annotations, Moshi moshi) {
    Class<?> rawType = Types.getRawType(type);
    if (!rawType.isAnnotationPresent(AlwaysSerializeNulls.class)) {
      return null;
    }

    JsonAdapter<Object> delegate = moshi.nextAdapter(this, type, annotations);
    return delegate.serializeNulls();
  }
}
Kotlin
class AlwaysSerializeNullsFactory : JsonAdapter.Factory {
  override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*>? {
    val rawType: Class<*> = type.rawType
    if (!rawType.isAnnotationPresent(AlwaysSerializeNulls::class.java)) {
      return null
    }
    val delegate: JsonAdapter<Any> = moshi.nextAdapter(this, type, annotations)
    return delegate.serializeNulls()
  }
}

After determining that it applies, the factory looks up Moshi's built-in adapter by calling Moshi.nextAdapter(). This is key to the composition mechanism: adapters delegate to each other! The composition in this example is simple: it applies the serializeNulls() transform on the delegate.

Composing adapters can be very sophisticated:

  • An adapter could transform the input object before it is JSON-encoded. A string could be trimmed or truncated; a value object could be simplified or normalized.

  • An adapter could repair the output object after it is JSON-decoded. It could fill-in missing data or discard unwanted data.

  • The JSON could be given extra structure, such as wrapping values in objects or arrays.

Moshi is itself built on the pattern of repeatedly composing adapters. For example, Moshi's built-in adapter for List<T> delegates to the adapter of T, and calls it repeatedly.

Precedence

Moshi's composition mechanism tries to find the best adapter for each type. It starts with the first adapter or factory registered with Moshi.Builder.add(), and proceeds until it finds an adapter for the target type.

If a type can be matched multiple adapters, the earliest one wins.

To register an adapter at the end of the list, use Moshi.Builder.addLast() instead. This is most useful when registering general-purpose adapters, such as the KotlinJsonAdapterFactory below.

Kotlin

Moshi is a great JSON library for Kotlin. It understands Kotlin’s non-nullable types and default parameter values. When you use Kotlin with Moshi you may use reflection, codegen, or both.

Reflection

The reflection adapter uses Kotlin’s reflection library to convert your Kotlin classes to and from JSON. Enable it by adding the KotlinJsonAdapterFactory to your Moshi.Builder:

val moshi = Moshi.Builder()
    .addLast(KotlinJsonAdapterFactory())
    .build()

Moshi’s adapters are ordered by precedence, so you should use addLast() with KotlinJsonAdapterFactory, and add() with your custom adapters.

The reflection adapter requires the following additional dependency:

<dependency>
  <groupId>com.squareup.moshi</groupId>
  <artifactId>moshi-kotlin</artifactId>
  <version>1.15.1</version>
</dependency>
implementation("com.squareup.moshi:moshi-kotlin:1.15.1")

Note that the reflection adapter transitively depends on the kotlin-reflect library which is a 2.5 MiB .jar file.

Codegen

Moshi’s Kotlin codegen support can be used as an annotation processor (via kapt) or Kotlin SymbolProcessor (KSP). It generates a small and fast adapter for each of your Kotlin classes at compile-time. Enable it by annotating each class that you want to encode as JSON:

@JsonClass(generateAdapter = true)
data class BlackjackHand(
  val hidden_card: Card,
  val visible_cards: List<Card>
)

The codegen adapter requires that your Kotlin types and their properties be either internal or public (this is Kotlin’s default visibility).

Kotlin codegen has no additional runtime dependency. You’ll need to enable kapt or KSP and then add the following to your build to enable the annotation processor:

KSP
plugins {
  id("com.google.devtools.ksp").version("1.6.10-1.0.4") // Or latest version of KSP
}

dependencies {
  ksp("com.squareup.moshi:moshi-kotlin-codegen:1.15.1")
}
Kapt
<dependency>
  <groupId>com.squareup.moshi</groupId>
  <artifactId>moshi-kotlin-codegen</artifactId>
  <version>1.15.1</version>
  <scope>provided</scope>
</dependency>
kapt("com.squareup.moshi:moshi-kotlin-codegen:1.15.1")

Limitations

If your Kotlin class has a superclass, it must also be a Kotlin class. Neither reflection or codegen support Kotlin types with Java supertypes or Java types with Kotlin supertypes. If you need to convert such classes to JSON you must create a custom type adapter.

The JSON encoding of Kotlin types is the same whether using reflection or codegen. Prefer codegen for better performance and to avoid the kotlin-reflect dependency; prefer reflection to convert both private and protected properties. If you have configured both, generated adapters will be used on types that are annotated @JsonClass(generateAdapter = true).

Download

Download the latest JAR or depend via Maven:

<dependency>
  <groupId>com.squareup.moshi</groupId>
  <artifactId>moshi</artifactId>
  <version>1.15.1</version>
</dependency>

or Gradle:

implementation("com.squareup.moshi:moshi:1.15.1")

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

R8 / ProGuard

Moshi contains minimally required rules for its own internals to work without need for consumers to embed their own. However if you are using reflective serialization and R8 or ProGuard, you must add keep rules in your proguard configuration file for your reflectively serialized classes.

Enums

Annotate enums with @JsonClass(generateAdapter = false) to prevent them from being removed/obfuscated from your code by R8/ProGuard.

License

Copyright 2015 Square, Inc.

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.

More Repositories

1

okhttp

Square’s meticulous HTTP client for the JVM, Android, and GraalVM.
Kotlin
45,794
star
2

retrofit

A type-safe HTTP client for Android and the JVM
HTML
43,053
star
3

leakcanary

A memory leak detection library for Android.
Kotlin
29,383
star
4

picasso

A powerful image downloading and caching library for Android
Kotlin
18,716
star
5

javapoet

A Java API for generating .java source files.
Java
10,820
star
6

okio

A modern I/O library for Android, Java, and Kotlin Multiplatform.
Kotlin
8,790
star
7

dagger

A fast dependency injector for Android and Java.
Java
7,308
star
8

crossfilter

Fast n-dimensional filtering and grouping of records.
JavaScript
6,217
star
9

PonyDebugger

Remote network and data debugging for your native iOS app using Chrome Developer Tools
Objective-C
5,864
star
10

maximum-awesome

Config files for vim and tmux.
Ruby
5,706
star
11

otto

An enhanced Guava-based event bus with emphasis on Android support.
Java
5,163
star
12

cubism

Cubism.js: A JavaScript library for time series visualization.
JavaScript
4,943
star
13

sqlbrite

A lightweight wrapper around SQLiteOpenHelper which introduces reactive stream semantics to SQL operations.
Java
4,570
star
14

android-times-square

Standalone Android widget for picking a single date from a calendar view.
Java
4,445
star
15

wire

gRPC and protocol buffers for Android, Kotlin, Swift and Java.
Kotlin
4,244
star
16

Valet

Valet lets you securely store data in the iOS, tvOS, watchOS, or macOS Keychain without knowing a thing about how the Keychain works. It’s easy. We promise.
Swift
3,989
star
17

cube

Cube: A system for time series visualization.
JavaScript
3,904
star
18

kotlinpoet

A Kotlin API for generating .kt source files.
Kotlin
3,896
star
19

java-code-styles

IntelliJ IDEA code style settings for Square's Java and Android projects.
Shell
2,957
star
20

flow

Name UI states, navigate between them, remember where you've been.
Java
2,786
star
21

spoon

Distributing instrumentation tests to all your Androids.
HTML
2,702
star
22

keywhiz

A system for distributing and managing secrets
Java
2,619
star
23

tape

A lightning fast, transactional, file-based FIFO for Android and Java.
Java
2,466
star
24

certstrap

Tools to bootstrap CAs, certificate requests, and signed certificates.
Go
2,282
star
25

mortar

A simple library that makes it easy to pair thin views with dedicated controllers, isolated from most of the vagaries of the Activity life cycle.
Java
2,157
star
26

go-jose

An implementation of JOSE standards (JWE, JWS, JWT) in Go
1,975
star
27

Cleanse

Lightweight Swift Dependency Injection Framework
Swift
1,784
star
28

assertj-android

A set of AssertJ helpers geared toward testing Android.
Java
1,577
star
29

haha

DEPRECATED Java library to automate the analysis of Android heap dumps.
Java
1,436
star
30

phrase

Phrase is an Android string resource templating library
Java
1,404
star
31

cane

Code quality threshold checking as part of your build
Ruby
1,325
star
32

anvil

A Kotlin compiler plugin to make dependency injection with Dagger 2 easier.
Kotlin
1,310
star
33

seismic

Android device shake detection.
Java
1,275
star
34

sudo_pair

Plugin for sudo that requires another human to approve and monitor privileged sudo sessions
Rust
1,240
star
35

square.github.io

A simple, static portal which outlines our open source offerings.
CSS
1,153
star
36

spacecommander

Commit fully-formatted Objective-C as a team without even trying.
Objective-C
1,126
star
37

workflow

A Swift and Kotlin library for making composable state machines, and UIs driven by those state machines.
Shell
1,124
star
38

workflow-kotlin

A Swift and Kotlin library for making composable state machines, and UIs driven by those state machines.
Kotlin
1,027
star
39

certigo

A utility to examine and validate certificates in a variety of formats
Go
941
star
40

logcat

I CAN HAZ LOGZ?
Kotlin
895
star
41

radiography

Text-ray goggles for your Android UI.
Kotlin
852
star
42

whorlwind

Makes fingerprint encryption a breeze.
Java
817
star
43

dagger-intellij-plugin

An IntelliJ IDEA plugin for Dagger which provides insight into how injections and providers are used.
Java
796
star
44

cycler

Kotlin
791
star
45

Paralayout

Paralayout is a set of simple, useful, and straightforward utilities that enable pixel-perfect layout in iOS. Your designers will love you.
Swift
786
star
46

apropos

A simple way to serve up appropriate images for every visitor.
Ruby
764
star
47

shift

shift is an application that helps you run schema migrations on MySQL databases
Ruby
735
star
48

coordinators

Simple MVWhatever for Android
Java
702
star
49

subzero

Block's Bitcoin Cold Storage solution.
C
683
star
50

Blueprint

Declarative UI construction for iOS, written in Swift
Swift
672
star
51

shuttle

String extraction, translation and export tools for the 21st century. "Moving strings around so you don't have to"
Ruby
656
star
52

gifencoder

A pure Java library implementing the GIF89a specification. Suitable for use on Android.
Java
654
star
53

pollexor

Java client for the Thumbor image service which allows you to build URIs in an expressive fashion using a fluent API.
Java
633
star
54

intro-to-d3

a D3.js tutorial
CSS
602
star
55

kochiku

Shard your builds for fun and profit
Ruby
599
star
56

curtains

Lift the curtain on Android Windows!
Kotlin
570
star
57

svelte-store

TypeScript
524
star
58

RxIdler

An IdlingResource for Espresso which wraps an RxJava Scheduler.
Java
511
star
59

burst

A unit testing library for varying test data.
Java
464
star
60

field-kit

FieldKit lets you take control of your text fields.
JavaScript
463
star
61

SuperDelegate

SuperDelegate provides a clean application delegate interface and protects you from bugs in the application lifecycle
Swift
454
star
62

otto-intellij-plugin

An IntelliJ IDEA plugin to navigate between events posted by Otto.
Java
451
star
63

js-jose

JavaScript library to encrypt/decrypt data in JSON Web Encryption (JWE) format and to sign/verify data in JSON Web Signature (JWS) format. Leverages Browser's native WebCrypto API.
JavaScript
422
star
64

sharkey

Sharkey is a service for managing certificates for use by OpenSSH
Go
395
star
65

connect-api-examples

Code samples demonstrating the functionality of the Square Connect API
JavaScript
391
star
66

fdoc

Documentation format and verification
Ruby
380
star
67

ETL

Extract, Transform, and Load data with Ruby
Ruby
377
star
68

lgtm

Simple object validation for JavaScript.
JavaScript
370
star
69

papa

PAPA: Performance of Android Production Applications
Kotlin
345
star
70

laravel-hyrule

Object-oriented, composable, fluent API for writing validations in Laravel
PHP
341
star
71

in-app-payments-flutter-plugin

Flutter Plugin for Square In-App Payments SDK
Objective-C
340
star
72

pylink

Python Library for device debugging/programming via J-Link
Python
331
star
73

workflow-swift

A Swift and Kotlin library for making composable state machines, and UIs driven by those state machines.
Swift
326
star
74

pysurvival

Open source package for Survival Analysis modeling
HTML
319
star
75

rails-auth

Modular resource-based authentication and authorization for Rails/Rack
Ruby
291
star
76

cocoapods-generate

A CocoaPods plugin that allows you to easily generate a workspace from a podspec.
Ruby
279
star
77

inspect

inspect is a collection of metrics gathering, analysis utilities for various subsystems of linux, mysql and postgres.
Go
268
star
78

Aardvark

Aardvark is a library that makes it dead simple to create actionable bug reports.
Objective-C
260
star
79

gradle-dependencies-sorter

A CLI app and Gradle plugin to sort the dependencies in your Gradle build scripts
Kotlin
253
star
80

jetpack

jet.pack: package your JRuby rack app for Jetty.
Ruby
248
star
81

luhnybin

Shell
232
star
82

auto-value-redacted

An extension for Google's AutoValue that omits redacted fields from toString().
Java
211
star
83

protoparser

Java parser for .proto schema declarations.
Java
210
star
84

squalor

Go SQL utility library
Go
205
star
85

Listable

Declarative list views for iOS apps.
Swift
200
star
86

p2

Platypus Platform: Tools for Scalable Deployment
Go
196
star
87

mimecraft

Utility for creating RFC-compliant multipart and form-encoded HTTP request bodies.
Java
195
star
88

git-fastclone

git clone --recursive on steroids
Ruby
187
star
89

zapp

Continuous Integration for KIF
Objective-C
179
star
90

metrics

Metrics Query Engine
Go
170
star
91

ruby-rrule

RRULE expansion for Ruby
Ruby
170
star
92

quotaservice

The purpose of a quota service is to prevent cascading failures in micro-service environments. The service acts as a traffic cop, slowing down traffic where necessary to prevent overloading services. For this to work, remote procedure calls (RPCs) between services consult the quota service before making a call. The service isn’t strictly for RPCs between services, and can even be used to apply quotas to database calls, for example.
Go
153
star
93

wire-gradle-plugin

A Gradle plugin for generating Java code for your protocol buffer definitions with Wire.
Groovy
153
star
94

goprotowrap

A package-at-a-time wrapper for protoc, for generating Go protobuf code.
Go
148
star
95

beancounter

Utility to audit the balance of Hierarchical Deterministic (HD) wallets. Supports multisig + segwit wallets.
Go
144
star
96

rce-agent

gRPC-based Remote Command Execution Agent
Go
136
star
97

womeng_handbook

Everything you need to start or expand a women in engineering group in your community.
129
star
98

cocoapods-check

A CocoaPods plugin that shows differences between locked and installed Pods
Ruby
126
star
99

point-of-sale-android-sdk

A simple library for letting Point of Sale take in-store payments for your app using Point of Sale API.
Java
119
star
100

in-app-payments-react-native-plugin

Objective-C
119
star