GithubHelp home page GithubHelp logo

square / moshi Goto Github PK

View Code? Open in Web Editor NEW
9.5K 182.0 745.0 4.84 MB

A modern JSON library for Kotlin and Java.

Home Page: https://square.github.io/moshi/1.x/

License: Apache License 2.0

Shell 0.08% Java 40.48% Kotlin 59.45%

moshi's Introduction

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.

moshi's People

Contributors

daugeldauge avatar dragonsinth avatar egorand avatar gabrielittner avatar goooler avatar jakewharton avatar jawnnypoo avatar k163377 avatar louiscad avatar macisamuele avatar nightlynexus avatar oldergod avatar renovate[bot] avatar rharter avatar robstoll avatar sampathkumaramex avatar sangeetds avatar sangho-block avatar satoshun avatar serj-lotutovici avatar shalomhalbert avatar spencergriffin avatar sullis avatar swankjesse avatar technoir42 avatar tolriq avatar valfirst avatar wasabi375 avatar yogurtearl avatar zacsweers avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

moshi's Issues

@NonNull support for fields

It would be cool if Moshi would throw an exception if a field was annotated with @NonNull but fromJson() would assign null to it.

Custom adapter's annotations with Proguard

Is there a configuration to make moshi work with Proguard? specifically the @FromJson and ToJson annotation?

I figured if I put this:

-keep class com.squareup.moshi.** { *; }
-keepattributes *Annotation*

it might work but I get Expected at least one @ToJson or @FromJson method on com.example.app.mypackage. Since it works perfectly when proguard is off, I'm guessing my configuration is wrong. Thanks in advance :)

Support magical toJson(), fromJson() methods

Classes can declare the following methods:

 <any access modifier> Object toJson();
 <any access modifier> public static Object fromJson(Object json);

If they do, Moshi honors ‘em. The returned objects are then themselves converted to JSON. The idea is that if you’re implementing a library class (say OkHttp’s Request) it can define it’s own JSON form without a compile-time dependency on Moshi. If this works I’ll talk to Tatu (Jackson) and Inder/Joel (gson) to try to make it a universally-supported pattern.

How do you convert jsonarray to List<Something>

Specifically how do you get an adapter for this type of structure?

Quasi code for reference:

String json = "[
{ "name" : "foo" },
{ "name" : "bar"}
]";

public class Name {
public final String name;
...
}

Moshi moshi = new Moshi.Builder().build().
JsonAdapter<???> adapter = moshi.adapter(??)
List names = adapter.fromJson(json);

JsonQualifier adapter doesn't get applied

I try to use Moshi in my Kotlin project which needs to parse a heterogeneous data as strings: it can be values like 5stars, something, true - and I need to parse them all as string. But when Moshi sees true it tries to parse it as boolean and throws an exception when parsing 3rd item:

com.squareup.moshi.JsonDataException: Expected a string but was BOOLEAN at path $.Data.FilterDictionary[5].Items[0].Options[1].Value

So I tried to come up with custom adapter and @JsonQualifier:

data class DictionaryEntry(
  val Options: List<Property>
)

data class Property(
  val Name: String,
  @ForceToString
  val Value: String
)

@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class ForceToString

class ForceToStringAdapter {
  @ToJson
  fun toJson(@ForceToString value: String): String = value
  @FromJson @ForceToString
  fun fromJson(value: String): String = throw UnsupportedOperationException()
//  fun fromJson(value: String): String = value
}

I register it:

    val moshi = Moshi.Builder()
      .add(ForceToStringAdapter())
      .build()
    val retrofit = Retrofit.Builder()
      .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
      .addConverterFactory(MoshiConverterFactory.create(moshi))
      .client(client)
      .baseUrl("...")
      .build()

But alas, nothing happens - same error about Boolean and no UnsupportedOperationException() gets thrown as I would expect from the above code...

I don't know if this is some library error or if I am doing something wrong or If this is something Kotlin specific.

Deploy javadoc

Copy script from other project. Set up empty gh-pages branch before running.

Writing a generic JsonAdapter.Factory for PVector<T>

Hello,

I am currently trying to replace Gson in one of my projects with Moshi - everything is working great so far, but there is one point I'd like to ask for a bit of guidance.

I am often using PVectors from http://pcollections.org/ to have immutable Lists in my data objects. For Gson I was using this:

public class PCollectionsAdapterFactory implements TypeAdapterFactory {

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {

    Type type = typeToken.getType();
    if (typeToken.getRawType() != PVector.class
            || !(type instanceof ParameterizedType)) {
        return null;
    }

    Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
    TypeAdapter<?> elementAdapter = gson.getAdapter(TypeToken.get(elementType));
    return (TypeAdapter<T>) createPVectorAdapter(elementAdapter);
}

private <T> TypeAdapter<PVector<T>> createPVectorAdapter(final TypeAdapter<T> elementAdapter) {
    return new TypeAdapter<PVector<T>>() {
        public void write(JsonWriter out, PVector<T> value) throws IOException {
            if (value == null) {
                out.nullValue();
                return;
            }

            out.beginArray();
            for (T element : value) {
                elementAdapter.write(out, element);
            }
            out.endArray();
        }

        public PVector<T> read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return null;
            }

            PVector<T> result = TreePVector.<T>empty();
            in.beginArray();
            while (in.hasNext()) {
                T element = elementAdapter.read(in);
                result = result.plus(element);
            }
            in.endArray();
            return result;
        }
    };
}
}

For Moshi I rewrote this like this:

public class PCollectionsAdapterFactory implements JsonAdapter.Factory {

@Override
public JsonAdapter<?> create(Type type, Set<? extends Annotation> annotations, Moshi moshi) {
    Class<?> rawType = Types.getRawType(type);

    if (!annotations.isEmpty()) return null;
    if (rawType == PVector.class) {
        return newPVectorAdapter(type, moshi);
    } else {
        return null;
    }
}

private static <T> JsonAdapter<PVector<T>> newPVectorAdapter(Type type, Moshi moshi) {
    Type elementType = Types.collectionElementType(type, Collection.class);
    JsonAdapter<T> elementAdapter = moshi.adapter(elementType);
    return new PVectorAdapter<T>(elementAdapter);
}

private static class PVectorAdapter<T> extends JsonAdapter<PVector<T>> {
    private final JsonAdapter<T> elementAdapter;

    public PVectorAdapter(JsonAdapter<T> elementAdapter) {
        this.elementAdapter = elementAdapter;
    }

    @Override
    public PVector<T> fromJson(JsonReader reader) throws IOException {
        if (reader.peek() == JsonReader.Token.NULL) {
            reader.nextNull();
            return null;
        }

        PVector<T> result = TreePVector.<T>empty();
        reader.beginArray();
        while (reader.hasNext()) {
            T element = elementAdapter.fromJson(reader);
            result = result.plus(element);
        }
        reader.endArray();
        return result;
    }

    @Override
    public void toJson(JsonWriter writer, PVector<T> value) throws IOException {
        if (value == null) {
            writer.nullValue();
            return;
        }

        writer.beginArray();
        for (T element : value) {
            elementAdapter.toJson(writer, element);
        }
        writer.endArray();
    }
}
}

And this seems to work fine, too. However I had to copy your whole Types class to my package to have access to Types.getRawType and Types.collectionElementType - do you have any plans to make all these methods public for use in custom JsonAdapter.Factorys or am I just using Moshi wrong?

Also, this seemed to work:

PVector<Channel> channels = startupResponse.channelMetaData.channelList;
try {
    final String channelsAsString = mMoshi.adapter(PVector.class).toJson(channels);
    Timber.d("CHANNELS AS JSON:\n%s", channelsAsString);
    final PVector<Channel> channelsAsPVectorAgain = mMoshi.adapter(PVector.class).fromJson(channelsAsString);
    Timber.d("CHANNELS AS PVECTOR AGAIN:\n%s", channelsAsPVectorAgain);
}

The crucial part here is adapter(PVector.class) - for Gson I always had to do something like new TypeToken<PVector<Channel>>(){}.getType() to deserialize a generic class. Is Moshi just easier that way or am I doing something wrong?

Any replies greatly appreciated!

David

Convert List<MyModel> to JSON

I would like to have the ability to convert something like
List myModelList = new ArrayList();
To JSON. The easiest way I can find and the GSON kind of way to do it is:
moshi.adapter(Types.newParameterizedType(List.class, MyModel.class);

The problem is the Types package is private. Am I missing something or can we make this package or method public so I can easily convert a list to JSON.

Custom converter get stucked if no value is read.

This one took us sometime to narrow down. So while stubbing out a custom converter class for a fast setup before starting with TDD, I wrote the implementation as the following:

@FromJson
public MyClass read(JsonReader reader) throws IOException {
    // TODO: write actual implementation
    return new MyClass();
}

The program crashed with an OOM exception and we had no idea why until we tried adding the following:

@FromJson
public MyClass read(JsonReader reader) throws IOException {
    // TODO: write actual implementation
    while(reader.hasNext()) {
        reader.skipValue();
    }
    return new MyClass();
}

Seems like the class that calls this converter via reflection, is waiting for it to consume it all while continuously allocating memory(?). I might be wrong, but I believe this is a bug.

@Json annotation to override the field name

An example:

class Customer {
  @Json("full name")
  String fullName;
}

(We won't support general policy-based name mangling, like converting camelCase to snake_case or kabob-case)

Allow null-values for primitive types

Gson and Moshi differ in their deserialization of null to primitive types:

  • Gson allows null for a primitive type, like int. It will result in 0.
  • Moshi is strict in this way and will throw an exception.

While I understand that the model should be Integer in cases where null is expected/allowed, this difference in both libraries makes the migration difficult.

Do you plan to allow null for primitive types? Maybe not by default but as an option on Moshi.Builder? If not this difference should at least be mentioned in the README.md.

JsonWriter.value() for (char[], offset, length) or CharSequence ?

JsonReader & JsonWriter handles utf8 values (and bytes) internally...which is good for performance reasons

Does it make sense (performance/safety) to have a public api for utf8 ByteString/chars/CharSequence values for JsonReader/Jsonwriter, to prevent object allocation/garbage collection/unnecessary transformations ?

If possible, I would like to avoid this :
{code}
writer.value(charSequence.toString())
{code}

Serialize Map in Kotlin

When you try to serialize Map<String,String>, Kotlin actually generates wildcards, i.e. ? extends String. This seems to confuse Moshi
Moshi tries to generate an adapter for ? extends String which is the type of the Map's values but doesn't check the default adapters.
Thanks to @cypressious for his remarks

v0.10 release?

I would love to use the new @Json annotation introduced by #68, but aside from the snapshot releases it is not included in any official release yet. Would you consider publishing a v0.10 release from the current master until all remaining issues for v1.0 are resolved?

Support for updating an object from a keypath/value?

I have a project where it's necessary to be able to modify a client-side object based on a JSON keypath/value pair that's sent over a persistent websocket. Is this something that's on the roadmap with Moshi?

Use case:

Say we have (excuse the useless example)

{
"kitchen": {
    "fridge": {
        "apple": {
            "status": "ok"
        },
        "pear": {
            "status": "ok"
        },
        "curry": {
            "status": "ok"
        }
    },
    "pantry": {
        "biscuit": {
            "status": "ok"
        },
        "chocolate": {
            "status": "ok"
        }
    }
}

}

At some point, the server says that the apples have gone out of date. Instead of sending over the whole kitchen, it'll do something like :

{"kitchen.fridge.apple.status": "moldy"}

Based on the server sending that over, the client side kitchen should be updated to have a moldy apple.

Here's another explanation & accompanying library (which doesn't actually work out of the box).
http://www.arg3.com/blog/2014/02/20/java-key-path-json-objects/

I modified that library a little, and have cobbled together an ugly working solution, but essentially it works by

*. Parse (with Gson) my object into JSONObject kitchen.
*. Do kitchen.putKeyPath("fridge.apple.status", "moldy")
*. Parse the kitchen back into it's proper class with Gson

It feels very wrong, but I haven't been able to think of anything cleaner.

Is this something within the same problem domain as Moshi, or should it be a more standalone thing?

moshi.JsonDataException

I keep getting an

error fetching results: com.squareup.moshi.JsonDataException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at path $

I defined my Moshi adapter like this:
public class SearchJsonAdapter { @FromJson public List<Phrase> fromJson(SearchResult result) { return result.phrases; } }

My Retrofit2 api is defined like this:
@GET ("ac")Observable<Result<SearchResult>> fetchPhrases( @Query("q") String query, @Query("format") String format);

And the model for SearchResult is defined like this:
public final class SearchResult { public List<Phrase> phrases; }

So I am trying to fetch the following JSON: https://ac.duckduckgo.com/ac/?q=android&format=json
which would output this in the browser:

[
-{
phrase: "android device manager"
},
-{
phrase: "android"
},
{
phrase: "android apps"
}
]

Do you know what I did wrong in the Moshi code?

@Json annotation on enum values

Another difference between Gson and Moshi is, that Gson allows its @SerializedName annotation on enums:

enum CustomEnum {
  @SerializedName("not_a") a,
  b
}

@Test
public void testSerializedName() throws Exception {
  CustomEnum a = gson.getAdapter(CustomEnum.class).fromJson("not_a");
  assertThat(a).isEqualTo(CustomEnum.a);
}

@Test
public void testJson() throws Exception {
  CustomEnum a = moshi.adapter(CustomEnum.class).fromJson("not_a");
  assertThat(a).isEqualTo(CustomEnum.a);
}

This will work with Gson. Unfortunately, Moshi does not process its @Json annotation on enums.

Is this a desired behaviour is this just a missed edge case?

Android: failing to find adapter for a 'GenericArrayTypeImpl' type

We have an adapter in place to process byte[] as a base64 / base32 string. Everything works fine when a class has a byte[] field, but parsing json fails on Android when we have a field of type Map<String, byte[]>. The code below works in the standard JVM but fails on Android.

  class Base32Adapter extends JsonAdapter<byte[]>  {
    @Override
    public byte[] fromJson(JsonReader reader) throws IOException {
      String string = reader.nextString();
      return new BigInteger(string, 32).toByteArray();
    }

    @Override
    public void toJson(JsonWriter writer, byte[] bytes) throws IOException {
      String string = new BigInteger(bytes).toString(32);
      writer.value(string);
    }
  }

  static class FavoriteBytes {
    @Json(name = "Bytes")
    public Map<String, byte[]> keys;
  }

  @Test public void customAdapter() throws Exception {
    String jsonString = "{\"Bytes\":{\"jesse\":\"a\",\"jake\":\"1\"}}";
    Moshi binaryMoshi = new Moshi.Builder().add(byte[].class, new Base32Adapter()).build();
    FavoriteBytes fav = binaryMoshi.adapter(FavoriteBytes.class).fromJson(jsonString);

    assertThat(fav.keys).containsOnlyKeys("jesse", "jake");
    assertThat(fav.keys.get("jesse")).isEqualTo(new byte[] { 0xa });
    assertThat(fav.keys.get("jake")).isEqualTo(new byte[] { 0x1 });
  }

On Android, this fails with exception:

E/MoshiTest(18268): com.squareup.moshi.JsonDataException: Expected BEGIN_ARRAY but was STRING at path $.Keys.jesse
E/MoshiTest(18268):     at com.squareup.moshi.JsonReader.beginArray(JsonReader.java:346)
E/MoshiTest(18268):     at com.squareup.moshi.ArrayJsonAdapter.fromJson(ArrayJsonAdapter.java:53)
E/MoshiTest(18268):     at com.squareup.moshi.JsonAdapter$1.fromJson(JsonAdapter.java:68)
E/MoshiTest(18268):     at com.squareup.moshi.MapJsonAdapter.fromJson(MapJsonAdapter.java:68)
E/MoshiTest(18268):     at com.squareup.moshi.MapJsonAdapter.fromJson(MapJsonAdapter.java:29)
E/MoshiTest(18268):     at com.squareup.moshi.JsonAdapter$1.fromJson(JsonAdapter.java:68)
E/MoshiTest(18268):     at com.squareup.moshi.ClassJsonAdapter$FieldBinding.read(ClassJsonAdapter.java:183)
E/MoshiTest(18268):     at com.squareup.moshi.ClassJsonAdapter.fromJson(ClassJsonAdapter.java:144)
E/MoshiTest(18268):     at com.squareup.moshi.JsonAdapter$1.fromJson(JsonAdapter.java:68)
E/MoshiTest(18268):     at com.squareup.moshi.JsonAdapter.fromJson(JsonAdapter.java:33)
E/MoshiTest(18268):     at com.squareup.moshi.JsonAdapter.fromJson(JsonAdapter.java:37)
...

Support for custom java.lang.reflect.Type

Currently if someone creates a custom implementation of java.lang.reflect.Type (with a custom JsonAdapter respectively) the utility method Types.getRawType() will throw a IllegalArgumentException doe to support only for Class<?>, ParameterizedType e.t.c. A workaround for this would be to just use type instanceof MyCustomType in the adapter factory, but then the custom adapter has to be first in line, so that other adapters don't throw through Types.getRawType().

This is ok till the point when users of an api that defines the custom type (which is fully private and is an implementation detail) add their own adapters.

By trying to implement the ParameterizedType puts the curtom adapter in conflict with Moshi's collection adapters, and doesn't work more sophisticated use cases like MyCustomType[List<MyCustomType>].

Better error message for missing half of an adapter

Given

class AnInterfaceAdapter {
  @ToJson String to(AnInterface ai) {
    return "an_interface";
  }
}
Moshi moshi = new Moshi.Builder()
    .add(new AnInterfaceAdapter())
    .build();
moshi.adapter(AnInterface.class);

An error message is thrown saying no adapter could be found for AnInterface. This is not strictly true and misleading, the problem is that only a "to" adapter could be found but no "from" adapter. We should report a better error message.

Recipe for buffered value

I've a scenario where I need to know a peer in order to properly interpret the other. In this case, there's a type field and a value field. The value could be a short, int, long, or double. I don't want to depend on field declaration order.

I was thinking about how to defer the decision since JsonReader smartly handles numbers.

Ex.

JsonReader valueReader = null;
switch (reader.nextName()) {
  case "type":
    type = Type.fromValue(reader.nextString());
    break;
  case "value":
    valueReader = reader.bufferValue(); // similar to peek, except consumes the next value
    break;
--snip--

switch (type) {
  case I64:
    value = valueReader.nextLong();
    break;
  case DOUBLE:
    value = valueReader.nextDouble();
    break;
--snip--

Parsing fails on NULL field values

This JSON
{
"id":"2",
"name":"glpi",
"firstname":null
}

fails: Expected a value but was NULL at path $.firstname

class ObjectJsonAdapter in file StandardJsonAdapters.java
has switch (reader.peek()) {}
there are BEGIN_ARRAY, BEGIN_OBJECT, STRING, NUMBER, BOOLEAN
and noooooo NULL value among cases !!!

Moshi doesn't work with Android 2.3

In ClassFactory.get(), it uses reflection to get method ObjectStreamClass.getConstructorId(). However, the method is not available in Android 2.3. Is there any workaround? Or should there be at least some documentation for this?

Json response with Java keyword for parameter name

We have a case where our API has labeled a parameter as "default", which is a protected keyword that can't be used as a variable name in Java. Given that you can't rename parameters with @SerialedName, as in Gson, is there some way to maybe prepend a character like "_" to get around this?

How to parse a list?

I'm trying to parse a a list but I can't find docs on how to do that. I already made my custom adapter class, but when I do the following:

This doesn't work with lists

JsonAdapter<MyData> adapter = moshi.adapter(MyData.class)

This doesn't work

JsonAdapter<List> adapter = moshi.adapter(List.class)

How do I parse a List<MyData> ?

CollectionJsonAdapter crashes on JSON object

I am having an issue when an api returns an object or an array of objects depending on the number of results.
This behaviour currently crashes moshi with Expected BEGIN_ARRAY but was BEGIN_OBJECT
I am using the yahoo geolocation api and I have no way to alter the way it works.
Currently I use a custom JsonAdapter.Factory

Api example that responds with

Check the json field called place in examples above

Parsing json to file

Hello, I have some jsons which sometimes contain huge values (1+ MB), as images are base64 encoded in them. I know its not the best solution, but its on the server so lets say we cannot change it for now.
For example [{"image": "iAmALongBase64EncodedString"}]
What is the best way to decode the value and store it in a file for later use? Currently I parse that json value as a String, then write it to a file as an InputStream. However some devices get Out of Memory at parsing to a string as it can be huge. Is there any way of skipping the String part and write the value in a file as stream? Thanks!

Allow raw JSON values?

I have raw JSON on disk that I want to embed in side a wrapper JSON. It would be awesome to do something like (explicitly choosing horrible names and hook points before and after)

File fileWithJson = ...;
JsonWriter json = new JsonWriter(sink);
json.beginObject();
json.name("foo").aboutToAddExternalValue();
sink.writeAll(Okio.source(fileWithJson));
json.valueAddedExternallyTrustMeItsFine();
json.closeObject();

Or even:

json.name("foo").value(Okio.source(...))

Support for Moshi.Builder(Moshi.Builder) constructor or add method.

This may sound like a stupid request, and no other (know to me) json library allows such possibilities, but there is a case when this is very handy. I have the following setup:

  • One api client that uses Moshi for json parsing.
  • The api client is shipped with predefined pojos, some of which require custom adapter factories (set by the api client).
  • The api client is used by multiple teams (not only onsite).
  • Other teams consume other "private" apis. Which result in -> new pojos and eventually requirement to set new adapters/adapter factories.

The point is that the client could expose in it's builder methods that will just mirror the ones in Moshi.Builder (currently 4 of them), but a more cleaner solution, would be just have one method addAll(builder) or addFrom(builder).

Replace substring with Okio-native substring writes.

This is a tracking issue for the slight improvement that can be made whenever Okio 1.4 is released.

JsonWriter's string method has two calls to sink.writeUtf8(string.substring(#, #)) which will be able to be replaced by sink.writeUtf8(string, #, #). This avoids the String & backing char[] allocation as well as the data copy to only read it back out again for encoding.

Implements field naming strategy

Of course I understand there is no field naming strategy in moshi, but what is the reason?
I mean it seems very critical stuff for ordinary android or java developer because we don't want to create exceptional naming rule.

Moshi only access UTF8 string format?

My code:

  1. POJO class
    public class LoginResponse {
public Integer ClientID;
public String message;
public String result;
public String sessionID;

}

  1. My usage moshi library:
                        Moshi moshi = new Moshi.Builder()
                                .add(new LoginJsonAdapter())
                                .build();
                        Log.v("moshi", "moshi 2.3.2");
                        JsonAdapter<LoginResponse> jsonAdapter = moshi.adapter(LoginResponse.class);
                        LoginResponse loginResponse = jsonAdapter.fromJson(mSringModelResponse);
  1. My actual JSon from server, example:

mSringModelResponse is simple java String.

{"ClientID":1,"message":"","result":"OK","sessionID":"0213a0c8-01fff99-4f5c-ad96-e8ffddrreerra0cfac0"}

  1. but nothing happen, I'll see it on my LogCat. Should I convert mSringModelResponse in UTF-8 format? Or what is problem?

Please, help.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.