A modern JSON library for Kotlin and Java.

Related tags

JSON moshi


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

String json = ...;

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

BlackjackHand blackjackHand = jsonAdapter.fromJson(json);

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

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);

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:

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 {

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:

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);

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

Moshi moshi = new Moshi.Builder()
    .add(new CardAdapter())


  "hidden_card": "6S",
  "visible_cards": [

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:

class Event {
  String title;
  String beginDateAndTime;

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:

class EventJson {
  String title;
  String begin_date;
  String begin_time;

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.

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;

Again we register the adapter with Moshi.

Moshi moshi = new Moshi.Builder()
    .add(new EventJsonAdapter())

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

JsonAdapter<Event> jsonAdapter = moshi.adapter(Event.class);
Event 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:

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

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>.

String cardsJsonResponse = ...;
Type type = Types.newParameterizedType(List.class, Card.class);
JsonAdapter<List<Card>> adapter = moshi.adapter(type);
List<Card> cards = 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 objects have the same structure. But when they don't, Moshi has annotations to customize data binding.

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

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

With @Json its corresponding Java class is easy:

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


Because JSON field names are always defined with their Java fields, Moshi makes it easy to find fields when navigating between Java 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:

class Rectangle {
  int width;
  int height;
  int color;

But if we encoded the above Java 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:

public @interface HexColor {

Next apply this @HexColor annotation to the appropriate field:

class Rectangle {
  int width;
  int height;
  @HexColor int color;

And finally define a type adapter to handle it:

/** 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);

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.

Omit fields with transient

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:

public final class BlackjackHand {
  private int total;


By default, all fields are emitted when encoding JSON, and all fields are accepted when decoding JSON. Prevent a field from being included by adding Java’s transient keyword:

public final class BlackjackHand {
  private transient int total;


Transient 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.

Default Values & Constructors

When reading JSON that is missing a field, Moshi relies on the Java 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.

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:

class TournamentWithNullsAdapter {
  @ToJson void toJson(JsonWriter writer, Tournament tournament,
      JsonAdapter<Tournament> delegate) throws IOException {
    boolean wasSerializeNulls = writer.getSerializeNulls();
    try {
      delegate.toJson(writer, tournament);
    } finally {

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:

public @interface AlwaysSerializeNulls {}
static class Car {
  String make;
  String model;
  String color;

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.

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();

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.


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.


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.


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()

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:


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


Moshi’s Kotlin codegen support is an annotation processor. 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 and then add the following to your build to enable the annotation processor:


You must also have the kotlin-stdlib dependency on the classpath during compilation in order for the compiled code to have the required metadata annotations that Moshi's processor looks for.


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 the latest JAR or depend via Maven:


or Gradle:


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.


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


Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
See the License for the specific language governing permissions and
limitations under the License.
  • Build exception when using new Proguard rules

    Build exception when using new Proguard rules

    After updating to Moshi 1.7.0 and updating the Proguard-rules I've encountered a Gradle build exception:

    Exception while processing task java.io.IOException: proguard.ParseException: Use of generics not allowed for java type at '<1><2><3>JsonAdapter' in line 31 of file '/Library/TeamCity/buildAgent/work/3ce9226b513c2493/dummy/proguard/proguard-moshi.pro'

    I'm now using my old proguard rules, and the build works fine, but I would like to know how to use the new Proguard rules. Here's my current rules which seems to work fine:

    -dontwarn okio.** -dontwarn javax.annotation.** -keepclassmembers class * { @com.squareup.moshi.FromJson ; @com.squareup.moshi.ToJson ; } -keep @com.squareup.moshi.JsonQualifier interface * -keepclassmembers class kotlin.Metadata { public ; } -dontwarn org.jetbrains.annotations.** -keep class kotlin.Metadata { *; }

    -dontwarn kotlin.reflect.jvm.internal.** -keep class kotlin.reflect.jvm.internal.** { *; }

    opened by oleandre 37
  • Moshi 1.5 ignores @Json annotation on Kotlin class properties

    Moshi 1.5 ignores @Json annotation on Kotlin class properties

    class RestUserSubscriptionPackage(
            val id: Int,
            @Json(name = "package_id") val package_prototype_id: Int,
            @Json(name = "package") val package_prototype: RestSubscriptionPackage?,
            val job_credit: JobCredit,
            val starts_at: OffsetDateTime,
            val ends_at: OffsetDateTime

    package_prototype_id is always 0, package_prototype is always null.

    Works out-of-the-box in Moshi 1.4.

    Workaround: @field:Json

    opened by consp1racy 35
  • Moshi fails to process Kotlin 1.6 metadata

    Moshi fails to process Kotlin 1.6 metadata

    Caused by: java.lang.IllegalStateException: Could not parse metadata! This should only happen if you're using Kotlin <1.1.
    	at com.squareup.moshi.kotlinpoet.metadata.KotlinPoetMetadata.readKotlinClassMetadata(KotlinPoetMetadata.kt:89)
    	at com.squareup.moshi.kotlinpoet.metadata.KotlinPoetMetadata.toImmutableKmClass(KotlinPoetMetadata.kt:119)
    	at com.squareup.moshi.kotlin.codegen.MoshiCachedClassInspector.toImmutableKmClass(MoshiCachedClassInspector.kt:37)
    	at com.squareup.moshi.kotlin.codegen.MetadataKt.targetType(metadata.kt:139)
    	at com.squareup.moshi.kotlin.codegen.JsonClassCodegenProcessor.adapterGenerator(JsonClassCodegenProcessor.kt:148)

    Project with reproduction test-moshi-kotlin16.zip

    opened by max-kammerer 33
  • Failed to find the generated JsonAdapter class ClassNotFoundException

    Failed to find the generated JsonAdapter class ClassNotFoundException

    I have a class in Kotlin that looks like this:

     import com.squareup.moshi.JsonClass
    @JsonClass(generateAdapter = true)
    data class AnnotationData (
       public val description: String,
       public val mid: String,
       public val score: Float,
       public val topicality: Float) {
      companion object {
          val DEFAULT = AnnotationData("","", 0.0f, 0.0f)

    My Gradle file has this:

    apply plugin: 'kotlin-kapt'
    kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.6.0'

    I have this in another file...

       val moshi = Moshi.Builder()
                .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe())
        val annotationAdapter = moshi.adapter(AnnotationData::class.java)
        val issue = annotationAdapter.fromJson(labelAnnotation.toString())

    When I run the application (in Intellij FWIW) I see this:

    Exception in thread "main" java.lang.RuntimeException: Failed to find the generated JsonAdapter class for class com.myapp.gcv.kotlin.AnnotationData at com.squareup.moshi.StandardJsonAdapters.generatedAdapter(StandardJsonAdapters.java:249) at com.squareup.moshi.StandardJsonAdapters$1.create(StandardJsonAdapters.java:62) at com.squareup.moshi.Moshi.adapter(Moshi.java:130) at com.squareup.moshi.Moshi.adapter(Moshi.java:68) at com.myapp.gcv.kotlin.GVProcessor.examineResponse(GVProcessor.kt:117) at com.myapp.gcv.kotlin.GVProcessor.access$examineResponse(GVProcessor.kt:12) at com.myapp.gcv.kotlin.GVProcessor$scanImage$1.doResume(GVProcessor.kt:93) at kotlin.coroutines.experimental.jvm.internal.CoroutineImpl.resume(CoroutineImpl.kt:42) at kotlinx.coroutines.experimental.DispatchTask.run(CoroutineDispatcher.kt:129) at kotlinx.coroutines.experimental.EventLoopBase.processNextEvent(EventLoop.kt:147) at kotlinx.coroutines.experimental.BlockingCoroutine.joinBlocking(Builders.kt:236) at kotlinx.coroutines.experimental.BuildersKt.runBlocking(Builders.kt:174) at kotlinx.coroutines.experimental.BuildersKt.runBlocking$default(Builders.kt:167) at com.myapp.gcv.kotlin.GVProcessor.scanImage(GVProcessor.kt:58) at com.myapp.gcv.kotlin.GVProcessor.processImage(GVProcessor.kt:36) at com.myapp.gcv.kotlin.MainKt.main(Main.kt:43) Caused by: java.lang.ClassNotFoundException: com.myapp.gcv.kotlin.AnnotationDataJsonAdapter at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499) at java.base/java.lang.Class.forName0(Native Method) at java.base/java.lang.Class.forName(Class.java:374) at com.squareup.moshi.StandardJsonAdapters.generatedAdapter(StandardJsonAdapters.java:236) ... 15 more

    I cannot find any "AnnotationDataJsonAdapter" in the entire directory so I am assuming it really isn't being generated.

    opened by darrinps 32
  • Moshi slower than Gson reading quoted values.

    Moshi slower than Gson reading quoted values.

    Ran the following in large loops.

    try (com.google.gson.stream.JsonReader reader = new com.google.gson.stream.JsonReader(
        new InputStreamReader(Foo.class.getClassLoader().getResourceAsStream("foo.json"), UTF_8))) {
      while (reader.hasNext()) {


    try (JsonReader reader = JsonReader.of(
        Okio.buffer(Okio.source(Foo.class.getClassLoader().getResourceAsStream("foo.json"))))) {
      while (reader.hasNext()) {

    With foo.json containing a huge array of single-quoted longs, Gson was about 25% faster. With foo.json containing unquoted longs, Moshi was about as fast as Gson.

    I found this performance degradation in other quoted values, like nextString and nextName, too.

    I suspect it is the performance of nextQuotedValue and BufferedSource's indexOfElement. (I will have to learn how to use real measurement tools, but I wanted to file here to remember to get back to this after finding this last Friday.)

    opened by NightlyNexus 30
  • Kotlin Codegen Release Blockers

    Kotlin Codegen Release Blockers

    The code’s checked in but there’s some follow-ups to do before we can invite users to use it:

    • [x] kotlin-metadata dependency released in mavencentral (https://github.com/Takhion/kotlin-metadata/issues/5)
    • [x] constructor signature
    • [x] @JsonQualifier annotations
    • [x] @MoshiSerializable annotation and factory potentially in core
    • [x] ”Generated code; do not edit“ header
    opened by swankjesse 25
  • Add support for forcing Moshi to construct instances using a specified constructor

    Add support for forcing Moshi to construct instances using a specified constructor

    This PR implements a method to force Moshi to construct instances of specific types using a constructor annotation. The main use case is Kotlin, but I imagine this could apply to Java code as well. Consider the following example:

    data class Foo(val bar: Bar) {
      @delegate:Transient val fooBar by lazy { doSomethingWith(bar) }

    Currently, Moshi supports deserializing a JSON into this type by unsafely creating the object, bypassing the constructor. A workaround is the Kotlin no-arg plugin introduced in Kotlin 1.0.6 which generates an empty constructor for annotated classes, but unfortunately both ways are problematic, as they don't initialize the hidden delegate instance for the lazy property.

    This problem is solved by the PR. The following modification is required in the code:

    data class Foo @JsonConstructor constructor(val bar: Bar) {
      @delegate:Transient val fooBar by lazy { doSomethingWith(bar) }

    This change will tell Moshi to use the primary constructor to construct the object. The way Moshi generates values for the parameters of the constructor after this PR is pretty straight-forward:

    • Primitive types and their associated reference types get the default value, such as 0 for int and Integer, 0.0 for double and Double and so on.
    • Strings get "".
    • Interfaces get a proxy instance that simply throws on method calls.
    • Enums get the first value in the values field.
    • Other types are recursively constructed using ClassFactory.get(...).newInstance().

    To reduce cost, ClassFactory instances are cached. The reason why parameters of reference types aren't simply set to null is that constructors may check for parameters to be non-null. Kotlin does this by default.

    Afterwards, Moshi proceeds as normal by deserializing the JSON values into the appropriate fields of the newly created instance. However, since the real constructor was called, the delegate is initialized correctly.

    opened by cbruegg 24
  • How about a JSON parser code generator on top of Moshi?

    How about a JSON parser code generator on top of Moshi?

    Some people are very concerned about speed... especially when it comes to JSON parsing and reflection. So my question would be:

    Does it make sense for you guys to add a parser generator on top (something like ig-json-parser and LoganSquare)?

    opened by serj-lotutovici 24
  • Kotlin Code Gen module

    Kotlin Code Gen module

    This is an initial implementation of a code gen module. Originally from https://github.com/hzsweers/CatchUp/tree/master/tooling/moshkt

    There's three main components:

    • moshi-kotlin-codegen - the actually processor implementation
    • integration-test - An integration test. This contains ignored KotlinJsonAdapter tests (Jesse mentioned wanting them to be able to pass the same tests is the long term goal, so this gives something to chip at) and some basic data classes tests.
    • moshi-kotlin-codegen-runtime - A runtime artifact with the @MoshiSerializable annotation and its corresponding MoshiSerializableJsonAdapterFactory. The factory usage is optional, as one could write a factory generator if they wanted to.


    • Data classes
    • @Json annotations
    • Kotlin language features like nullability and default values (it generates Kotlin code via KotlinPoet, so it can actually leverage these features)
    • If a companion object is specified on the source type, it generates an extension jsonAdapter() function onto it
    • Generics
    • Good chunk of Kotshi tests


    • Support for more than just data classes
    • JsonQualifier annotations

    For data classes, it's been working swimmingly in CatchUp as well as @rharter's codebases. Code itself could probably use some cleaning up (there's plenty of TODOs left in), but its output seems to be working well so far.

    CC @Takhion


    data class Foo(
       @Json(name = "first_name") val firstName: String,
       @Json(name = "last_name") val lastName: String,
       val age: Int,
       val nationalities: List<String> = emptyList(),
       val weight: Float,
       val tattoos: Boolean = false,
       val race: String?,
       val hasChildren: Boolean = false,
       val favoriteFood: String? = null,
       val favoriteDrink: String? = "Water"


    package com.squareup.moshi
    import kotlin.Any
    import kotlin.Boolean
    import kotlin.Float
    import kotlin.Int
    import kotlin.String
    import kotlin.collections.List
    class Foo_JsonAdapter(moshi: Moshi) : JsonAdapter<Foo>() {
      private val string_Adapter: JsonAdapter<String> = moshi.adapter(String::class.java)
      private val int_Adapter: JsonAdapter<Int> = moshi.adapter(Int::class.java)
      private val list__string_Adapter: JsonAdapter<List<String>> = moshi.adapter<List<String>>(Types.newParameterizedType(List::class.java, String::class.java))
      private val float_Adapter: JsonAdapter<Float> = moshi.adapter(Float::class.java)
      private val boolean_Adapter: JsonAdapter<Boolean> = moshi.adapter(Boolean::class.java)
      override fun fromJson(reader: JsonReader): Foo? {
        if (reader.peek() == JsonReader.Token.NULL) {
        lateinit var firstName: String
        lateinit var lastName: String
        var age = 0
        var nationalities: List<String>? = null
        var weight = 0.0f
        var tattoos: Boolean? = null
        var race: String? = null
        var hasChildren: Boolean? = null
        var favoriteFood: String? = null
        var favoriteDrink: String? = null
        while (reader.hasNext()) {
          when (reader.selectName(OPTIONS)) {
            0 -> firstName = string_Adapter.fromJson(reader)!!
            1 -> lastName = string_Adapter.fromJson(reader)!!
            2 -> age = int_Adapter.fromJson(reader)!!
            3 -> nationalities = list__string_Adapter.fromJson(reader)!!
            4 -> weight = float_Adapter.fromJson(reader)!!
            5 -> tattoos = boolean_Adapter.fromJson(reader)!!
            6 -> race = string_Adapter.fromJson(reader)
            7 -> hasChildren = boolean_Adapter.fromJson(reader)!!
            8 -> favoriteFood = string_Adapter.fromJson(reader)
            9 -> favoriteDrink = string_Adapter.fromJson(reader)
            -1 -> {
              // Unknown name, skip it
        return Foo(firstName = firstName,
            lastName = lastName,
            age = age,
            weight = weight,
            race = race).let {
              it.copy(nationalities = nationalities ?: it.nationalities,
                  tattoos = tattoos ?: it.tattoos,
                  hasChildren = hasChildren ?: it.hasChildren,
                  favoriteFood = favoriteFood ?: it.favoriteFood,
                  favoriteDrink = favoriteDrink ?: it.favoriteDrink)
      override fun toJson(writer: JsonWriter, value: Foo?) {
        if (value == null) {
        string_Adapter.toJson(writer, value.firstName)
        string_Adapter.toJson(writer, value.lastName)
        int_Adapter.toJson(writer, value.age)
        list__string_Adapter.toJson(writer, value.nationalities)
        float_Adapter.toJson(writer, value.weight)
        boolean_Adapter.toJson(writer, value.tattoos)
        if (value.race != null) {
          string_Adapter.toJson(writer, value.race)
        boolean_Adapter.toJson(writer, value.hasChildren)
        if (value.favoriteFood != null) {
          string_Adapter.toJson(writer, value.favoriteFood)
        if (value.favoriteDrink != null) {
          string_Adapter.toJson(writer, value.favoriteDrink)
      private companion object SelectOptions {
        private val OPTIONS: JsonReader.Options by lazy { JsonReader.Options.of("first_name", "last_name", "age", "nationalities", "weight", "tattoos", "race", "hasChildren", "favoriteFood", "favoriteDrink") }
    opened by ZacSweers 23
  • IllegalArgumentException: wrong number of arguments

    IllegalArgumentException: wrong number of arguments

    In generated code

    @JsonClass(generateAdapter = true)
    data class Dashboard(
            val tabTitle1: String? = null,


        val localConstructor: Constructor<Dashboard> = this.constructorRef
            ?: Util.lookupDefaultsConstructor(Dashboard::class.java).also { this.constructorRef = it }
        return localConstructor.newInstance(

    in the latest snapshot, resulting in "java.lang.IllegalArgumentException: wrong number of arguments" for localConstructor.newInstance

    why "mask" and "null" are added?

    opened by ber4444 21
  • When using MoshiConverterFactory in retrofit, the first call blocks main thread

    When using MoshiConverterFactory in retrofit, the first call blocks main thread

    I am using the MoshiConverterFactory in an Android Application written in Kotlin in combination with Retrofit. The first call to retrofit's enqueue does not return directly like expected, but takes between one and two seconds to return blocking the UI thread and skipping up to 100 frames.
    The problem only occurs when using Moshi, with Gson as Adapter Factory the first call takes longer too, but only around 150ms.

    The code I'm using is:

    val time = measureTimeMillis {
        val call = geocodingApi.searchByName("Berlin")
        call.enqueue(object : Callback<GeocodingResponse> {
            override fun onResponse(call: Call<GeocodingResponse>?, response: Response<GeocodingResponse>?) {
              // some code
            override fun onFailure(call: Call<GeocodingResponse>?, t: Throwable?) {
              // some code
    Timber.d("searching by name took $time ms")

    The geocodingApi is initialised in the constructor of my class as follows:

    val loggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { Timber.d(it) })
    loggingInterceptor.level = HttpLoggingInterceptor.Level.HEADERS
    val client = OkHttpClient
    val retrofit = Retrofit.Builder()
    geocodingApi = retrofit.create(GeocodingApi::class.java)

    The logs look like this:

    searching by name took 1864 ms
    searching by name took 3 ms
    searching by name took 4 ms
    searching by name took 2 ms

    I created a sample application to verify the behaviour without my app code: https://github.com/Phoca/KotlinRetrofitMoshiTest

    Thanks for investigating!

    needs info 
    opened by Phocacius 20
  • @JsonQualifier Can't I turn an Object field into a JSON string?

    @JsonQualifier Can't I turn an Object field into a JSON string?

    Let's look directly at the example:

    annotation class ObjectToJson
    class ObjectToJsonAdapter {
        fun toJson(@ObjectToJson data: Any): String {
            return JSON.toJSONString(data)
        fun fromJson(data: Any): Any {
            return data
    data class OperateGroup(
        var id: String? = null,
        var name: String? = null,
        var illustrate: String? = null,
        var level: String? = null,
        var pack: String? = null,
        @ObjectToJson var payload: GroupPayload = GroupPayload(),
        var ownerLabel: String? = null
    ) : Parcelable
    data class GroupPayload(
        var lat_lon: String = ""
    ) : Parcelable
    private val retrofit = Retrofit.Builder()

    An error message is reported:

    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.example.sproutapp, PID: 5121
        java.lang.IllegalArgumentException: Unable to create converter for com.example.sproutapp.entity.Result<com.example.sproutapp.api.members.BaseStatisticData>
            for method OperateGroupAPI.baseStatistic
            at retrofit2.Utils.methodError(Utils.java:54)
            at retrofit2.HttpServiceMethod.createResponseConverter(HttpServiceMethod.java:126)
            at retrofit2.HttpServiceMethod.parseAnnotations(HttpServiceMethod.java:85)
            at retrofit2.ServiceMethod.parseAnnotations(ServiceMethod.java:39)
            at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:202)
            at retrofit2.Retrofit$1.invoke(Retrofit.java:160)
            at java.lang.reflect.Proxy.invoke(Proxy.java:1006)
            at $Proxy7.baseStatistic(Unknown Source)
            at com.example.sproutapp.store.FixedResources.update(FixedResources.kt:45)
            at com.example.sproutapp.SproutAppState$loginNavigate$1.invokeSuspend(SproutAppState.kt:130)
            at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
            at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
            at androidx.compose.ui.platform.AndroidUiDispatcher.performTrampolineDispatch(AndroidUiDispatcher.android.kt:81)
            at androidx.compose.ui.platform.AndroidUiDispatcher.access$performTrampolineDispatch(AndroidUiDispatcher.android.kt:41)
            at androidx.compose.ui.platform.AndroidUiDispatcher$dispatchCallback$1.run(AndroidUiDispatcher.android.kt:57)
            at android.os.Handler.handleCallback(Handler.java:938)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loopOnce(Looper.java:210)
            at android.os.Looper.loop(Looper.java:299)
            at android.app.ActivityThread.main(ActivityThread.java:8293)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1045)
        	Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [androidx.compose.ui.platform.MotionDurationScaleImpl@aa9c863, androidx.compose.runtime.BroadcastFrameClock@4eaac60, StandaloneCoroutine{Cancelling}@ab0d519, AndroidUiDispatcher@88e89de]
        Caused by: java.lang.IllegalArgumentException: No JsonAdapter for class com.example.sproutapp.api.members.GroupPayload annotated [@com.example.sproutapp.model.ObjectToJson()]
        for class com.example.sproutapp.api.members.GroupPayload payload
        for class com.example.sproutapp.api.members.OperateGroup
        for java.util.List<com.example.sproutapp.api.members.OperateGroup> groupList
        for class com.example.sproutapp.api.members.BaseStatisticData data
        for com.example.sproutapp.entity.Result<com.example.sproutapp.api.members.BaseStatisticData>
            at com.squareup.moshi.Moshi$LookupChain.exceptionWithLookupStack(Moshi.java:389)
            at com.squareup.moshi.Moshi.adapter(Moshi.java:158)
            at com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory.create(KotlinJsonAdapter.kt:292)
            at com.squareup.moshi.Moshi.adapter(Moshi.java:146)
            at com.squareup.moshi.Moshi.adapter(Moshi.java:106)
            at com.squareup.moshi.Moshi.adapter(Moshi.java:75)
            at com.squareup.moshi.CollectionJsonAdapter.newArrayListAdapter(CollectionJsonAdapter.java:54)
            at com.squareup.moshi.CollectionJsonAdapter$1.create(CollectionJsonAdapter.java:38)
            at com.squareup.moshi.Moshi.adapter(Moshi.java:146)
            at com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory.create(KotlinJsonAdapter.kt:292)
            at com.squareup.moshi.Moshi.adapter(Moshi.java:146)
            at com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory.create(KotlinJsonAdapter.kt:292)
            at com.squareup.moshi.Moshi.adapter(Moshi.java:146)
            at com.squareup.moshi.Moshi.adapter(Moshi.java:106)
            at retrofit2.converter.moshi.MoshiConverterFactory.responseBodyConverter(MoshiConverterFactory.java:89)
            at retrofit2.Retrofit.nextResponseBodyConverter(Retrofit.java:362)
            at retrofit2.Retrofit.responseBodyConverter(Retrofit.java:345)
            at retrofit2.HttpServiceMethod.createResponseConverter(HttpServiceMethod.java:124)
            	... 21 more
    E/AndroidRuntime: Caused by: java.lang.IllegalArgumentException: No JsonAdapter for class com.example.sproutapp.api.members.GroupPayload annotated [@com.example.sproutapp.model.ObjectToJson()]
            at com.squareup.moshi.Moshi.adapter(Moshi.java:156)
            	... 37 more
    opened by XiaoyuZhann 0
  • [FEATURE] New factory API to control the type `labelKey` serialization.

    [FEATURE] New factory API to control the type `labelKey` serialization.


    New API autoSerializeLabel(boolean) added to allow the factory can be configured with boolean flag to disable automatic serialization of the type label, and it's respective value. Here is how the configuration may look like in the factory builder.

    PolymorphicJsonAdapterFactory.of(Message.class, "type")
        .withSubtype(Success.class, "success")
        .withSubtype(MessageWithType.class, "customType")
        .autoSerializeLabel(false)) // ← New API!

    This is done for use cases when all known subtypes has serializable type property in the class definition, then it generates double type properties when serialized to JSON.

    Background of the change

    There are two key reason for requesting this feature (new API).

    1. In projects, sub-type classes can have type property which is serializable. Adding @Json(ignore = true) is not an option. That results in double type value in the serialized JSON object.
    2. There are some use cases where serializing object via parent type is not always applicable (eg Message in this example). When sub-type has type class property, it can be serialized directly without using polymorphic adapter (eg. MessageWithType in this example). Having this API would allow to have type property in class and allow it to play nicely with polymorphic adapter when deserializing as well.

    ✅ Signed "Square Inc. Individual Contributor License Agreement" for my GitHub username.

    opened by hossain-khan 2
  • Adding support for inline classes and unsigned integers

    Adding support for inline classes and unsigned integers

    The intention of this pull request is to address the issues outlined in #1170.

    This would also cover the unsigned types [ULong, UInt, UShort, UByte].

    I've outlined the thought process and approach for this solution in this repository, including the expected behavior, the current behavior (as of version 1.14.0) and the behavior after this addition of the included adapters.

    Any & all feedback is highly appreciated!

    opened by amichne 0
  • [ver. 1.14.0] Adapter generation fails if JsonQualifier has nested annotations

    [ver. 1.14.0] Adapter generation fails if JsonQualifier has nested annotations

    Minimal setup to reproduce:

    @JsonClass(generateAdapter = true)
    data class MessageConnectionTest(
        var node: String? = null
    annotation class DecodeTypesTest(
        vararg val value: DecodeTypeTest
    annotation class DecodeTypeTest(val name: String)

    Moshi 1.12.0 + kotlin 1.5.0 + kapt generates proper adapter with the following internal val (full generated adapter attached in zip):

      @field:DecodeTypesTest(value = [DecodeTypeTest(name = "TextMessage")])
      private val nullableStringAtDecodeTypesTestAdapter: JsonAdapter<String?> =
          moshi.adapter(String::class.java, Types.getFieldJsonQualifierAnnotations(javaClass,
          "nullableStringAtDecodeTypesTestAdapter"), "node")

    Moshi 1.14.0 + kotlin 1.6.21 + kapt generates adapter with the following internal val (this generated adapter also attached in zip):

      private val nullableStringAtDecodeTypesTestAdapter: JsonAdapter<String?> =
          moshi.adapter(String::class.java, setOf(DecodeTypesTest(value = arrayOf(@DecodeTypeTest(name =
          "TextMessage")))), "node")

    Compilation of this code fails with an error "Expecting an element", because "@DecodeTypeTest" was generated instead of "DecodeTypeTest".


    opened by lev-zakaryan 0
  • please add support for JPMS via a module-info.java or at least a module name in the jar's manifest

    please add support for JPMS via a module-info.java or at least a module name in the jar's manifest

    without a jar specifying a module name or having a module-info JPMS will use the jar name as an automatic module. For some users this will be fine but for library projects that publish to maven repositories this is not ok. Hence seeing warning messages like this:

    * Required filename-based automodules detected: [moshi-1.14.0.jar]. Please don't publish this project to a public artifact repository! *

    personally I would much have a world where everything in maven central contained a module-info.java but at least specifying the Automatic-Module-Name in the jar's manifest would be beneficial.

    opened by SingingBush 0
Images grid JSON | Сетка изображений JSON

Images grid JSON | Сетка изображений JSON Задача Разработать приложение: Приложение должно получать JSON-список ссылок на изображения с сервера по адр

Sefo Notasi 2 Apr 25, 2022
Modern JSON processor with readable Kotlin syntax.

Kq Modern cross-platform JSON processor with readable Kotlin syntax. cat ~/Desktop/bdb.ndjson | kq '.filter{it.bool("muted")}.sortedBy{it.long("size")

Daniel Demidko 6 Jan 25, 2022
Manager of progress using Lottie JSON, compatible for Java and Kotlin.

Progress Lottie IGB Manager of progress using Lottie JSON, compatible for Java and Kotlin. Int Top In Bottom Important Info: To create a raw folder: R

Isaac G. Banda 21 Sep 16, 2022
Fast JSON parser for java projects

ig-json-parser Fast JSON parser for java projects. Getting started The easiest way to get started is to look at maven-example. For more comprehensive

Instagram 1.3k Dec 29, 2022
Customizable JSON Schema-based forms for Kotlin and Compose

Kotlin JSON Forms Customizable JSON Schema-based forms for Kotlin and Compose This project aims to reimplement JSON Forms in Kotlin for use in Compose

Copper Leaf 3 Oct 1, 2022
A lightweight Kotlin DSL to render DSL style Json to String.

A lightweight Kotlin DSL to render DSL style Json to String.

null 4 May 5, 2021
xls2json - Read in Excel file (.xls, .xlsx, .xlsm) and output JSON

xls2json Read in Excel file (.xls, .xlsx, .xlsm) and output JSON. Evaluates formulas where possible. Preserve type information from Excel via JSON typ

Tammo Ippen 39 Oct 19, 2022
Simple CLI app to convert XML retrieved from a configurable URI to JSON and back

XmlToJsonUtility Simple CLI app written in Kotlin (1.5.31) on Java 11, using Spring Boot. Queries a URI (default) as an XML source. Attempts to valida

Darius Washington 2 Oct 20, 2021
ktlint JSON Lines reporter

ktlint JSON Lines reporter Usage Download the jar and run: ktlint --reporter=jsonlines,artifact=ktlint-jsonlines-reporter.jar Download Either downloa

Anton Musichin 1 Nov 24, 2021
Generate a JSON bookmarks document from a GitHub user

Github to bookmarks This little webapp will generate a JSON bookmarks document from a GitHub user. This is intended to be used with bbt. An instance i

Benoit Lubek 2 Nov 8, 2021
A Shopping cart library for Android that allows you add to add items to cart and retrieve at ease using JSONObjects.

Carteasy A Shopping cart library for Android that allows you add to add items to cart and retrieve at ease using JSONObjects. Quick Start Add the foll

Tosin Onikute 25 Oct 19, 2022
Kotlin extensions for Moshi, Make every thing you want with Moshi in just one line.

Kotlin extensions for Moshi, Make every thing with square / Moshi in one line.

Mazen Rashed 15 Nov 21, 2021
Pojson provides Kotlin DSL for building complex jsons in declarative manner.

Pojson is a kotlin library for json prototyping. It brings DSL for building JsonObjectPrototype and JsonArrayPrototype. Prototypes don't reference to any json object/array models.

Alexander Mironychev 5 Jan 4, 2022
🚀Plugin for Android Studio And IntelliJ Idea to generate Kotlin data class code from JSON text ( Json to Kotlin )

JsonToKotlinClass Hi, Welcome! This is a plugin to generate Kotlin data class from JSON string, in another word, a plugin that converts JSON string to

Seal 2.8k Jan 3, 2023
Android Material Json Form Wizard is a library for creating beautiful form based wizards within your app just by defining json in a particular format.

Android Json Wizard Android Json Wizard is a library for creating beautiful form based wizards within your app just by defining json in a particular f

Vijay Rawat 355 Nov 11, 2022
A Java serialization/deserialization library to convert Java Objects into JSON and back

Gson Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to a

Google 21.7k Jan 5, 2023
LiteHttp is a simple, intelligent and flexible HTTP framework for Android. With LiteHttp you can make HTTP request with only one line of code! It could convert a java model to the parameter and rander the response JSON as a java model intelligently.

Android network framework: LiteHttp Tags : litehttp2.x-tutorials Website : http://litesuits.com QQgroup : 42960650 , 47357508 Android网络通信为啥子选 lite-htt

马天宇 829 Dec 29, 2022
Images grid JSON | Сетка изображений JSON

Images grid JSON | Сетка изображений JSON Задача Разработать приложение: Приложение должно получать JSON-список ссылок на изображения с сервера по адр

Sefo Notasi 2 Apr 25, 2022
Dynamic-UI-From-JSON - A Sample Android app to show dynamic UI generation from Json

Dynamic UI from JSON Functionality The app's functionality includes: The app gen

Rafsan Ahmad 12 Dec 16, 2022
I was fed up with writing Java classes to mirror json models. So I wrote this Java app to automate the process.

Json2Java I was fed up with writing Java classes to mirror json models. So I wrote this Java app to automate the process. What this tool can do right

Jon F Hancock 303 Oct 8, 2022