Standard Adapters

Moshi comes with a set of built-in adapters for standard Java and Kotlin types, located in the core moshi artifact. These are registered by default and handle most common use cases.

Primitive Types

Moshi has built-in adapters for all of Java's primitive types and their boxed counterparts:

  • boolean / Boolean
  • byte / Byte
  • char / Character
  • double / Double
  • float / Float
  • int / Integer
  • long / Long
  • short / Short

Primitive types are non-nullable, while their boxed counterparts are nullable.

String

java.lang.String is supported out of the box.

Enums

Enums are serialized by their constant name. For example, Suit.CLUBS is serialized as the JSON string "CLUBS".

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

You can customize the serialized name using the @Json annotation:

enum class Roshambo {
  ROCK,
  PAPER,
  @Json(name = "scr") SCISSORS
}
// Roshambo.SCISSORS serializes to "scr"

If Moshi encounters a JSON string that doesn't match any enum constant, it will throw a JsonDataException. For more advanced enum handling, see the EnumJsonAdapter in the moshi-adapters module.

Collections

Moshi provides default adapters for standard collection interfaces:

  • java.util.List
  • java.util.Set
  • java.util.Collection

These are serialized as JSON arrays. When deserializing, Moshi creates ArrayList and LinkedHashSet instances respectively.

Maps

java.util.Map is supported and is serialized as a JSON object. By default, map keys are serialized to strings. If you have non-string keys, Moshi will call toString() on them.

Arrays

Both primitive arrays (int[], boolean[], etc.) and object arrays (String[]) are supported and are serialized as JSON arrays.

The Object Adapter

Moshi includes a special adapter for java.lang.Object. This adapter is polymorphic and handles different types at runtime.

  • Serialization: When serializing an Object, Moshi inspects the runtime type of the value and delegates to the specific adapter for that type. For example, if the Object is actually a String, it will use the String adapter. If it's a List, it will use the List adapter.
  • Deserialization: When deserializing to Object, Moshi uses a set of default types:
    • JSON objects become Map<String, Object>.
    • JSON arrays become List<Object>.
    • JSON strings become String.
    • JSON numbers become Double.
    • JSON booleans become Boolean.
    • JSON null becomes null.