Package com.squareup.moshi

Types

AdapterMethodsFactory
Link copied to clipboard
class AdapterMethodsFactory : JsonAdapter.Factory
ArrayJsonAdapter
Link copied to clipboard

Converts arrays to JSON arrays containing their converted contents. This supports both primitive and object arrays.

class ArrayJsonAdapter : JsonAdapter<Any>
ClassFactory
Link copied to clipboard

Magic that creates instances of arbitrary concrete classes. Derived from Gson's UnsafeAllocator and ConstructorConstructor classes.

abstract class ClassFactory<T>
ClassJsonAdapter
Link copied to clipboard

Emits a regular class as a JSON object by mapping Java fields to JSON object properties.

Platform Types Fields from platform classes are omitted from both serialization and deserialization unless they are either public or protected. This includes the following packages and their subpackages:
  • android.*
  • androidx.*
  • java.*
  • javax.*
  • kotlin.*
  • kotlinx.*
  • scala.*

class ClassJsonAdapter<T> : JsonAdapter<T>
CollectionJsonAdapter
Link copied to clipboard

Converts collection types to JSON arrays containing their converted contents.

abstract class CollectionJsonAdapter<C : Collection<T>?, T> : JsonAdapter<C>
FromJson
Link copied to clipboard
annotation class FromJson
Json
Link copied to clipboard

Customizes how a field is encoded as JSON.

Although this annotation doesn't declare a Target , it is only honored in the following elements:

  • Java class fields
  • Kotlin properties for use with {@code moshi-kotlin} . This includes both properties declared in the constructor and properties declared as members.

Users of the AutoValue: Moshi Extension may also use this annotation on abstract getters.

@Retention(value = )
annotation class Json
JsonAdapter
Link copied to clipboard

Converts Java values to JSON, and JSON values to Java.

JsonAdapter instances provided by Moshi are thread-safe, meaning multiple threads can safely use a single instance concurrently.

Custom JsonAdapter implementations should be designed to be thread-safe.

abstract class JsonAdapter<T>
JsonClass
Link copied to clipboard

Customizes how a type is encoded as JSON.

@Retention(value = )
annotation class JsonClass
JsonDataException
Link copied to clipboard

Thrown when the data in a JSON document doesn't match the data expected by the caller. For example, suppose the application expects a boolean but the JSON document contains a string. When the call to nextBoolean is made, a {@code JsonDataException} is thrown.

Exceptions of this type should be fixed by either changing the application code to accept the unexpected JSON, or by changing the JSON to conform to the application's expectations.

This exception may also be triggered if a document's nesting exceeds 31 levels. This depth is sufficient for all practical applications, but shallow enough to avoid uglier failures like StackOverflowError .

class JsonDataException : RuntimeException
JsonEncodingException
Link copied to clipboard

Thrown when the data being parsed is not encoded as valid JSON.

class JsonEncodingException : IOException
JsonQualifier
Link copied to clipboard

Annotates another annotation, causing it to specialize how values are encoded and decoded.

@Target(value = )
@Retention(value = )
annotation class JsonQualifier
JsonReader
Link copied to clipboard

Reads a JSON (RFC 7159) encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document. Within JSON objects, name/value pairs are represented by a single token.

Parsing JSON To create a recursive descent parser for your own JSON streams, first create an entry point method that creates a {@code JsonReader} .

Next, create handler methods for each structure in your JSON text. You'll need a method for each object type and for each array type.

  • Within array handling methods, first call beginArray to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext is false. Finally, read the array's closing bracket by calling .
  • Within object handling methods, first call beginObject to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext is false. Finally, read the object's closing brace by calling endObject .

When a nested object or array is encountered, delegate to the corresponding handler method.

When an unknown name is encountered, strict parsers should fail with an exception. Lenient parsers should call skipValue to recursively skip the value's nested tokens, which may otherwise conflict.

If a value may be null, you should first check using peek . Null literals can be consumed using either nextNull or skipValue .

Example Suppose we'd like to parse a stream of messages such as the following:
{@code * [ * { * "id": 912345678901, * "text": "How do I read a JSON stream in Java?", * "geo": null, * "user": { * "name": "json_newb", * "followers_count": 41 * } * }, * { * "id": 912345678902, * "text": "@json_newb just use JsonReader!", * "geo": [50.454722, -104.606667], * "user": { * "name": "jesse", * "followers_count": 2 * } * } * ] * }
This code implements the parser for the above structure:
{@code * public ListreadJsonStream(BufferedSource source) throws IOException {
 *   JsonReader reader = JsonReader.of(source);
 *   try {
 *     return readMessagesArray(reader);
 *   } finally {
 *     reader.close();
 *   }
 * }
 *
 * public List
Number Handling This reader permits numeric values to be read as strings and string values to be read as numbers. For example, both elements of the JSON array {@code [1, "1"]} may be read using either or nextString . This behavior is intended to prevent lossy numeric conversions: double is JavaScript's only numeric type and very large values like {@code 9007199254740993} cannot be represented exactly on that platform. To minimize precision loss, extremely large values should be written and read as strings in JSON.

Each {@code JsonReader} may be used to read a single JSON stream. Instances of this class are not thread safe.

abstract class JsonReader : Closeable
JsonScope
Link copied to clipboard

Lexical scoping elements within a JSON reader or writer.

class JsonScope
JsonUtf8Reader
Link copied to clipboard
class JsonUtf8Reader : JsonReader
JsonUtf8Writer
Link copied to clipboard
class JsonUtf8Writer : JsonWriter
JsonValueReader
Link copied to clipboard

This class reads a JSON document by traversing a Java object comprising maps, lists, and JSON primitives. It does depth-first traversal keeping a stack starting with the root object. During traversal a stack tracks the current position in the document:

  • The next element to act upon is on the top of the stack.
  • When the top of the stack is a List , calling beginArray replaces the list with a JsonIterator . The first element of the iterator is pushed on top of the iterator.
  • Similarly, when the top of the stack is a Map , calling beginObject replaces the map with an JsonIterator of its entries. The first element of the iterator is pushed on top of the iterator.
  • When the top of the stack is a Map.Entry , calling nextName returns the entry's key and replaces the entry with its value on the stack.
  • When an element is consumed it is popped. If the new top of the stack has a non-exhausted iterator, the next element of that iterator is pushed.
  • If the top of the stack is an exhausted iterator, calling endArray or will pop it.

class JsonValueReader : JsonReader
JsonValueSource
Link copied to clipboard

This source reads a prefix of another source as a JSON value and then terminates. It can read top-level arrays, objects, or strings only.

It implements lenient parsing and has no mechanism to enforce strict parsing. If the input is not valid or lenient JSON the behavior of this source is unspecified.

class JsonValueSource : Source
JsonValueWriter
Link copied to clipboard

Writes JSON by building a Java object comprising maps, lists, and JSON primitives.

class JsonValueWriter : JsonWriter
JsonWriter
Link copied to clipboard

Writes a JSON (RFC 7159) encoded value to a stream, one token at a time. The stream includes both literal values (strings, numbers, booleans and nulls) as well as the begin and end delimiters of objects and arrays.

Encoding JSON To encode your data as JSON, create a new {@code JsonWriter} . Each JSON document must contain one top-level array or object. Call methods on the writer as you walk the structure's contents, nesting arrays and objects as necessary:
  • To write arrays, first call beginArray . Write each of the array's elements with the appropriate methods or by nesting other arrays and objects. Finally close the array using endArray .
  • To write objects, first call beginObject . Write each of the object's properties by alternating calls to name with the property's value. Write property values with the appropriate method or by nesting other objects or arrays. Finally close the object using endObject .
Example Suppose we'd like to encode a stream of messages such as the following:
{@code * [ * { * "id": 912345678901, * "text": "How do I stream JSON in Java?", * "geo": null, * "user": { * "name": "json_newb", * "followers_count": 41 * } * }, * { * "id": 912345678902, * "text": "@json_newb just use JsonWriter!", * "geo": [50.454722, -104.606667], * "user": { * "name": "jesse", * "followers_count": 2 * } * } * ] * }
This code encodes the above structure:
{@code * public void writeJsonStream(BufferedSink sink, Listmessages) throws IOException {
 *   JsonWriter writer = JsonWriter.of(sink);
 *   writer.setIndent("  ");
 *   writeMessagesArray(writer, messages);
 *   writer.close();
 * }
 *
 * public void writeMessagesArray(JsonWriter writer, List

Each {@code JsonWriter} may be used to write a single JSON stream. Instances of this class are not thread safe. Calls that would result in a malformed JSON string will fail with an .

abstract class JsonWriter : Closeable, Flushable
LinkedHashTreeMap
Link copied to clipboard

A map of comparable keys to values. Unlike {@code TreeMap} , this class uses insertion order for iteration order. Comparison order is only used as an optimization for efficient insertion and removal.

This implementation was derived from Android 4.1's TreeMap and LinkedHashMap classes.

class LinkedHashTreeMap<K, V> : AbstractMap<K, V> , Serializable
MapJsonAdapter
Link copied to clipboard

Converts maps with string keys to JSON objects.

TODO: support maps with other key types and convert to/from strings.

class MapJsonAdapter<K, V> : JsonAdapter<Map<K, V>>
Moshi
Link copied to clipboard

Coordinates binding between JSON values and Java objects.

Moshi instances are thread-safe, meaning multiple threads can safely use a single instance concurrently.

class Moshi
StandardJsonAdapters
Link copied to clipboard
class StandardJsonAdapters
ToJson
Link copied to clipboard
annotation class ToJson
Types
Link copied to clipboard

Factory methods for types.

class Types

Functions

adapter
Link copied to clipboard
inline fun <T> Moshi.adapter(): JsonAdapter<T>
fun <T> Moshi.adapter(ktype: KType): JsonAdapter<T>
addAdapter
Link copied to clipboard
inline fun <T> Moshi.Builder.addAdapter(adapter: JsonAdapter<T>): Moshi.Builder
asArrayType
Link copied to clipboard
fun Type.asArrayType(): GenericArrayType
fun KClass<*>.asArrayType(): GenericArrayType
fun KType.asArrayType(): GenericArrayType
nextAnnotations
Link copied to clipboard

Checks if this contains T. Returns the subset of this without T, or null if this does not contain T.

inline fun <T : Annotation> Set<Annotation>.nextAnnotations(): Set<Annotation>?
subtypeOf
Link copied to clipboard

Returns a type that represents an unknown type that extends T. For example, if T is CharSequence, this returns out CharSequence. If T is Any, this returns *, which is shorthand for out Any?.

inline fun <T> subtypeOf(): WildcardType
supertypeOf
Link copied to clipboard

Returns a type that represents an unknown supertype of T bound. For example, if T is String, this returns in String.

inline fun <T> supertypeOf(): WildcardType

Properties

rawType
Link copied to clipboard

Returns the raw Class type of this type.

val Type.rawType: Class<*>