{"id":3548,"url":"https://github.com/square/moshi","last_synced_at":"2025-05-12T16:25:04.469Z","repository":{"id":19541494,"uuid":"22789601","full_name":"square/moshi","owner":"square","description":"A modern JSON library for Kotlin and Java.","archived":false,"fork":false,"pushed_at":"2025-05-01T02:56:22.000Z","size":4889,"stargazers_count":9899,"open_issues_count":114,"forks_count":767,"subscribers_count":183,"default_branch":"master","last_synced_at":"2025-05-05T14:18:34.550Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://square.github.io/moshi/1.x/","language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/square.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2014-08-09T15:58:42.000Z","updated_at":"2025-05-02T16:40:39.000Z","dependencies_parsed_at":"2023-11-19T15:25:46.711Z","dependency_job_id":"437027df-3c5d-4f33-98dc-69e2a08ef79f","html_url":"https://github.com/square/moshi","commit_stats":{"total_commits":727,"total_committers":93,"mean_commits":7.817204301075269,"dds":0.7427785419532325,"last_synced_commit":"3d9d6042b39fefb557bc485315473854e8c622f7"},"previous_names":[],"tags_count":25,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/square%2Fmoshi","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/square%2Fmoshi/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/square%2Fmoshi/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/square%2Fmoshi/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/square","download_url":"https://codeload.github.com/square/moshi/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253774952,"owners_count":21962256,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-01-05T20:16:44.618Z","updated_at":"2025-05-12T16:25:04.449Z","avatar_url":"https://github.com/square.png","language":"Kotlin","readme":"Moshi\n=====\n\nMoshi is a modern JSON library for Android, Java and Kotlin. It makes it easy to parse JSON into Java and Kotlin\nclasses:\n\n_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._\n\n\u003cdetails\u003e\n  \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nString json = ...;\n\nMoshi moshi = new Moshi.Builder().build();\nJsonAdapter\u003cBlackjackHand\u003e jsonAdapter = moshi.adapter(BlackjackHand.class);\n\nBlackjackHand blackjackHand = jsonAdapter.fromJson(json);\nSystem.out.println(blackjackHand);\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n  \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nval json: String = ...\n\nval moshi: Moshi = Moshi.Builder().build()\nval jsonAdapter: JsonAdapter\u003cBlackjackHand\u003e = moshi.adapter\u003cBlackjackHand\u003e()\n\nval blackjackHand = jsonAdapter.fromJson(json)\nprintln(blackjackHand)\n```\n\u003c/details\u003e\n\nAnd it can just as easily serialize Java or Kotlin objects as JSON:\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nBlackjackHand blackjackHand = new BlackjackHand(\n    new Card('6', SPADES),\n    Arrays.asList(new Card('4', CLUBS), new Card('A', HEARTS)));\n\nMoshi moshi = new Moshi.Builder().build();\nJsonAdapter\u003cBlackjackHand\u003e jsonAdapter = moshi.adapter(BlackjackHand.class);\n\nString json = jsonAdapter.toJson(blackjackHand);\nSystem.out.println(json);\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nval blackjackHand = BlackjackHand(\n    Card('6', SPADES),\n    listOf(Card('4', CLUBS), Card('A', HEARTS))\n  )\n\nval moshi: Moshi = Moshi.Builder().build()\nval jsonAdapter: JsonAdapter\u003cBlackjackHand\u003e = moshi.adapter\u003cBlackjackHand\u003e()\n\nval json: String = jsonAdapter.toJson(blackjackHand)\nprintln(json)\n```\n\u003c/details\u003e\n\n### Built-in Type Adapters\n\nMoshi has built-in support for reading and writing Java’s core data types:\n\n * Primitives (int, float, char...) and their boxed counterparts (Integer, Float, Character...).\n * Arrays, Collections, Lists, Sets, and Maps\n * Strings\n * Enums\n\nIt supports your model classes by writing them out field-by-field. In the example above Moshi uses\nthese classes:\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nclass BlackjackHand {\n  public final Card hidden_card;\n  public final List\u003cCard\u003e visible_cards;\n  ...\n}\n\nclass Card {\n  public final char rank;\n  public final Suit suit;\n  ...\n}\n\nenum Suit {\n  CLUBS, DIAMONDS, HEARTS, SPADES;\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nclass BlackjackHand(\n  val hidden_card: Card,\n  val visible_cards: List\u003cCard\u003e,\n  ...\n)\n\nclass Card(\n  val rank: Char,\n  val suit: Suit\n  ...\n)\n\nenum class Suit {\n  CLUBS, DIAMONDS, HEARTS, SPADES;\n}\n```\n\u003c/details\u003e\n\n\nto read and write this JSON:\n\n```json\n{\n  \"hidden_card\": {\n    \"rank\": \"6\",\n    \"suit\": \"SPADES\"\n  },\n  \"visible_cards\": [\n    {\n      \"rank\": \"4\",\n      \"suit\": \"CLUBS\"\n    },\n    {\n      \"rank\": \"A\",\n      \"suit\": \"HEARTS\"\n    }\n  ]\n}\n```\n\nThe [Javadoc][javadoc] catalogs the complete Moshi API, which we explore below.\n\n### Custom Type Adapters\n\nWith Moshi, it’s particularly easy to customize how values are converted to and from JSON. A type\nadapter is any class that has methods annotated `@ToJson` and `@FromJson`.\n\nFor example, Moshi’s default encoding of a playing card is verbose: the JSON defines the rank and\nsuit in separate fields: `{\"rank\":\"A\",\"suit\":\"HEARTS\"}`. With a type adapter, we can change the\nencoding to something more compact: `\"4H\"` for the four of hearts or `\"JD\"` for the jack of\ndiamonds:\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nclass CardAdapter {\n  @ToJson String toJson(Card card) {\n    return card.rank + card.suit.name().substring(0, 1);\n  }\n\n  @FromJson Card fromJson(String card) {\n    if (card.length() != 2) throw new JsonDataException(\"Unknown card: \" + card);\n\n    char rank = card.charAt(0);\n    switch (card.charAt(1)) {\n      case 'C': return new Card(rank, Suit.CLUBS);\n      case 'D': return new Card(rank, Suit.DIAMONDS);\n      case 'H': return new Card(rank, Suit.HEARTS);\n      case 'S': return new Card(rank, Suit.SPADES);\n      default: throw new JsonDataException(\"unknown suit: \" + card);\n    }\n  }\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nclass CardAdapter {\n  @ToJson fun toJson(card: Card): String {\n    return card.rank + card.suit.name.substring(0, 1)\n  }\n\n  @FromJson fun fromJson(card: String): Card {\n    if (card.length != 2) throw JsonDataException(\"Unknown card: $card\")\n\n    val rank = card[0]\n    return when (card[1]) {\n      'C' -\u003e Card(rank, Suit.CLUBS)\n      'D' -\u003e Card(rank, Suit.DIAMONDS)\n      'H' -\u003e Card(rank, Suit.HEARTS)\n      'S' -\u003e Card(rank, Suit.SPADES)\n      else -\u003e throw JsonDataException(\"unknown suit: $card\")\n    }\n  }\n}\n```\n\u003c/details\u003e\n\nRegister the type adapter with the `Moshi.Builder` and we’re good to go.\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nMoshi moshi = new Moshi.Builder()\n    .add(new CardAdapter())\n    .build();\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nval moshi = Moshi.Builder()\n    .add(CardAdapter())\n    .build()\n```\n\u003c/details\u003e\n\nVoilà:\n\n```json\n{\n  \"hidden_card\": \"6S\",\n  \"visible_cards\": [\n    \"4C\",\n    \"AH\"\n  ]\n}\n```\n\n#### Another example\n\nNote that the method annotated with `@FromJson` does not need to take a String as an argument.\nRather it can take input of any type and Moshi will first parse the JSON to an object of that type\nand then use the `@FromJson` method to produce the desired final value. Conversely, the method\nannotated with `@ToJson` does not have to produce a String.\n\nAssume, for example, that we have to parse a JSON in which the date and time of an event are\nrepresented as two separate strings.\n\n```json\n{\n  \"title\": \"Blackjack tournament\",\n  \"begin_date\": \"20151010\",\n  \"begin_time\": \"17:04\"\n}\n```\n\nWe would like to combine these two fields into one string to facilitate the date parsing at a\nlater point. Also, we would like to have all variable names in CamelCase. Therefore, the `Event`\nclass we want Moshi to produce like this:\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nclass Event {\n  String title;\n  String beginDateAndTime;\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nclass Event(\n  val title: String,\n  val beginDateAndTime: String\n)\n```\n\u003c/details\u003e\n\nInstead of manually parsing the JSON line per line (which we could also do) we can have Moshi do the\ntransformation automatically. We simply define another class `EventJson` that directly corresponds\nto the JSON structure:\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nclass EventJson {\n  String title;\n  String begin_date;\n  String begin_time;\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nclass EventJson(\n  val title: String,\n  val begin_date: String,\n  val begin_time: String\n)\n```\n\u003c/details\u003e\n\nAnd another class with the appropriate `@FromJson` and `@ToJson` methods that are telling Moshi how\nto convert an `EventJson` to an `Event` and back. Now, whenever we are asking Moshi to parse a JSON\nto an `Event` it will first parse it to an `EventJson` as an intermediate step. Conversely, to\nserialize an `Event` Moshi will first create an `EventJson` object and then serialize that object as\nusual.\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nclass EventJsonAdapter {\n  @FromJson Event eventFromJson(EventJson eventJson) {\n    Event event = new Event();\n    event.title = eventJson.title;\n    event.beginDateAndTime = eventJson.begin_date + \" \" + eventJson.begin_time;\n    return event;\n  }\n\n  @ToJson EventJson eventToJson(Event event) {\n    EventJson json = new EventJson();\n    json.title = event.title;\n    json.begin_date = event.beginDateAndTime.substring(0, 8);\n    json.begin_time = event.beginDateAndTime.substring(9, 14);\n    return json;\n  }\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nclass EventJsonAdapter {\n  @FromJson\n  fun eventFromJson(eventJson: EventJson): Event {\n    return Event(\n      title = eventJson.title,\n      beginDateAndTime = \"${eventJson.begin_date} ${eventJson.begin_time}\"\n    )\n  }\n\n  @ToJson\n  fun eventToJson(event: Event): EventJson {\n    return EventJson(\n      title = event.title,\n      begin_date = event.beginDateAndTime.substring(0, 8),\n      begin_time = event.beginDateAndTime.substring(9, 14),\n    )\n  }\n}\n```\n\u003c/details\u003e\n\nAgain we register the adapter with Moshi.\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nMoshi moshi = new Moshi.Builder()\n    .add(new EventJsonAdapter())\n    .build();\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nval moshi = Moshi.Builder()\n    .add(EventJsonAdapter())\n    .build()\n```\n\u003c/details\u003e\n\nWe can now use Moshi to parse the JSON directly to an `Event`.\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nJsonAdapter\u003cEvent\u003e jsonAdapter = moshi.adapter(Event.class);\nEvent event = jsonAdapter.fromJson(json);\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nval jsonAdapter = moshi.adapter\u003cEvent\u003e()\nval event = jsonAdapter.fromJson(json)\n```\n\u003c/details\u003e\n\n### Adapter convenience methods\n\nMoshi provides a number of convenience methods for `JsonAdapter` objects:\n- `nullSafe()`\n- `nonNull()`\n- `lenient()`\n- `failOnUnknown()`\n- `indent()`\n- `serializeNulls()`\n\nThese factory methods wrap an existing `JsonAdapter` into additional functionality.\nFor example, if you have an adapter that doesn't support nullable values, you can use `nullSafe()` to make it null safe:\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nString dateJson = \"\\\"2018-11-26T11:04:19.342668Z\\\"\";\nString nullDateJson = \"null\";\n\n// Hypothetical IsoDateDapter, doesn't support null by default\nJsonAdapter\u003cDate\u003e adapter = new IsoDateDapter();\n\nDate date = adapter.fromJson(dateJson);\nSystem.out.println(date); // Mon Nov 26 12:04:19 CET 2018\n\nDate nullDate = adapter.fromJson(nullDateJson);\n// Exception, com.squareup.moshi.JsonDataException: Expected a string but was NULL at path $\n\nDate nullDate = adapter.nullSafe().fromJson(nullDateJson);\nSystem.out.println(nullDate); // null\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nval dateJson = \"\\\"2018-11-26T11:04:19.342668Z\\\"\"\nval nullDateJson = \"null\"\n\n// Hypothetical IsoDateDapter, doesn't support null by default\nval adapter: JsonAdapter\u003cDate\u003e = IsoDateDapter()\n\nval date = adapter.fromJson(dateJson)\nprintln(date) // Mon Nov 26 12:04:19 CET 2018\n\nval nullDate = adapter.fromJson(nullDateJson)\n// Exception, com.squareup.moshi.JsonDataException: Expected a string but was NULL at path $\n\nval nullDate = adapter.nullSafe().fromJson(nullDateJson)\nprintln(nullDate) // null\n```\n\u003c/details\u003e\n\nIn contrast to `nullSafe()` there is `nonNull()` to make an adapter refuse null values. Refer to the Moshi JavaDoc for details on the various methods.\n\n### Parse JSON Arrays\n\nSay we have a JSON string of this structure:\n\n```json\n[\n  {\n    \"rank\": \"4\",\n    \"suit\": \"CLUBS\"\n  },\n  {\n    \"rank\": \"A\",\n    \"suit\": \"HEARTS\"\n  }\n]\n```\n\nWe can now use Moshi to parse the JSON string into a `List\u003cCard\u003e`.\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nString cardsJsonResponse = ...;\nType type = Types.newParameterizedType(List.class, Card.class);\nJsonAdapter\u003cList\u003cCard\u003e\u003e adapter = moshi.adapter(type);\nList\u003cCard\u003e cards = adapter.fromJson(cardsJsonResponse);\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nval cardsJsonResponse: String = ...\n// We can just use a reified extension!\nval adapter = moshi.adapter\u003cList\u003cCard\u003e\u003e()\nval cards: List\u003cCard\u003e = adapter.fromJson(cardsJsonResponse)\n```\n\u003c/details\u003e\n\n### Fails Gracefully\n\nAutomatic databinding almost feels like magic. But unlike the black magic that typically accompanies\nreflection, Moshi is designed to help you out when things go wrong.\n\n```\nJsonDataException: Expected one of [CLUBS, DIAMONDS, HEARTS, SPADES] but was ANCHOR at path $.visible_cards[2].suit\n  at com.squareup.moshi.JsonAdapters$11.fromJson(JsonAdapters.java:188)\n  at com.squareup.moshi.JsonAdapters$11.fromJson(JsonAdapters.java:180)\n  ...\n```\n\nMoshi always throws a standard `java.io.IOException` if there is an error reading the JSON document,\nor if it is malformed. It throws a `JsonDataException` if the JSON document is well-formed, but\ndoesn’t match the expected format.\n\n### Built on Okio\n\nMoshi uses [Okio][okio] for simple and powerful I/O. It’s a fine complement to [OkHttp][okhttp],\nwhich can share buffer segments for maximum efficiency.\n\n### Borrows from Gson\n\nMoshi uses the same streaming and binding mechanisms as [Gson][gson]. If you’re a Gson user you’ll\nfind Moshi works similarly. If you try Moshi and don’t love it, you can even migrate to Gson without\nmuch violence!\n\nBut the two libraries have a few important differences:\n\n * **Moshi has fewer built-in type adapters.** For example, you need to configure your own date\n   adapter. Most binding libraries will encode whatever you throw at them. Moshi refuses to\n   serialize platform types (`java.*`, `javax.*`, and `android.*`) without a user-provided type\n   adapter. This is intended to prevent you from accidentally locking yourself to a specific JDK or\n   Android release.\n * **Moshi is less configurable.** There’s no field naming strategy, versioning, instance creators,\n   or long serialization policy. Instead of naming a field `visibleCards` and using a policy class\n   to convert that to `visible_cards`, Moshi wants you to just name the field `visible_cards` as it\n   appears in the JSON.\n * **Moshi doesn’t have a `JsonElement` model.** Instead it just uses built-in types like `List` and\n   `Map`.\n * **No HTML-safe escaping.** Gson encodes `=` as `\\u003d` by default so that it can be safely\n   encoded in HTML without additional escaping. Moshi encodes it naturally (as `=`) and assumes that\n   the HTML encoder – if there is one – will do its job.\n\n### Custom field names with @Json\n\nMoshi works best when your JSON objects and Java or Kotlin classes have the same structure. But when they\ndon't, Moshi has annotations to customize data binding.\n\nUse `@Json` to specify how Java fields or Kotlin properties map to JSON names. This is necessary when the JSON name\ncontains spaces or other characters that aren’t permitted in Java field or Kotlin property names. For example, this\nJSON has a field name containing a space:\n\n```json\n{\n  \"username\": \"jesse\",\n  \"lucky number\": 32\n}\n```\n\nWith `@Json` its corresponding Java or Kotlin class is easy:\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nclass Player {\n  String username;\n  @Json(name = \"lucky number\") int luckyNumber;\n\n  ...\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nclass Player {\n  val username: String\n  @Json(name = \"lucky number\") val luckyNumber: Int\n\n  ...\n}\n```\n\u003c/details\u003e\n\nBecause JSON field names are always defined with their Java or Kotlin fields, Moshi makes it easy to find\nfields when navigating between Java or Koltin and JSON.\n\n### Alternate type adapters with @JsonQualifier\n\nUse `@JsonQualifier` to customize how a type is encoded for some fields without changing its\nencoding everywhere. This works similarly to the qualifier annotations in dependency injection\ntools like Dagger and Guice.\n\nHere’s a JSON message with two integers and a color:\n\n```json\n{\n  \"width\": 1024,\n  \"height\": 768,\n  \"color\": \"#ff0000\"\n}\n```\n\nBy convention, Android programs also use `int` for colors:\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nclass Rectangle {\n  int width;\n  int height;\n  int color;\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nclass Rectangle(\n  val width: Int,\n  val height: Int,\n  val color: Int\n)\n```\n\u003c/details\u003e\n\nBut if we encoded the above Java or Kotlin class as JSON, the color isn't encoded properly!\n\n```json\n{\n  \"width\": 1024,\n  \"height\": 768,\n  \"color\": 16711680\n}\n```\n\nThe fix is to define a qualifier annotation, itself annotated `@JsonQualifier`:\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\n@Retention(RUNTIME)\n@JsonQualifier\npublic @interface HexColor {\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\n@Retention(RUNTIME)\n@JsonQualifier\nannotation class HexColor\n```\n\u003c/details\u003e\n\n\nNext apply this `@HexColor` annotation to the appropriate field:\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nclass Rectangle {\n  int width;\n  int height;\n  @HexColor int color;\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nclass Rectangle(\n  val width: Int,\n  val height: Int,\n  @HexColor val color: Int\n)\n```\n\u003c/details\u003e\n\nAnd finally define a type adapter to handle it:\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\n/** Converts strings like #ff0000 to the corresponding color ints. */\nclass ColorAdapter {\n  @ToJson String toJson(@HexColor int rgb) {\n    return String.format(\"#%06x\", rgb);\n  }\n\n  @FromJson @HexColor int fromJson(String rgb) {\n    return Integer.parseInt(rgb.substring(1), 16);\n  }\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\n/** Converts strings like #ff0000 to the corresponding color ints.  */\nclass ColorAdapter {\n  @ToJson fun toJson(@HexColor rgb: Int): String {\n    return \"#%06x\".format(rgb)\n  }\n\n  @FromJson @HexColor fun fromJson(rgb: String): Int {\n    return rgb.substring(1).toInt(16)\n  }\n}\n```\n\u003c/details\u003e\n\nUse `@JsonQualifier` when you need different JSON encodings for the same type. Most programs\nshouldn’t need this `@JsonQualifier`, but it’s very handy for those that do.\n\n### Omitting fields\n\nSome models declare fields that shouldn’t be included in JSON. For example, suppose our blackjack\nhand has a `total` field with the sum of the cards:\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\npublic final class BlackjackHand {\n  private int total;\n\n  ...\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nclass BlackjackHand(\n  private val total: Int,\n\n  ...\n)\n```\n\u003c/details\u003e\n\nBy default, all fields are emitted when encoding JSON, and all fields are accepted when decoding\nJSON. Prevent a field from being included by annotating them with `@Json(ignore = true)`.\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\npublic final class BlackjackHand {\n  @Json(ignore = true)\n  private int total;\n\n  ...\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nclass BlackjackHand(...) {\n  @Json(ignore = true)\n  var total: Int = 0\n\n  ...\n}\n```\n\u003c/details\u003e\n\nThese fields are omitted when writing JSON. When reading JSON, the field is skipped even if the\nJSON contains a value for the field. Instead, it will get a default value. In Kotlin, these fields\n_must_ have a default value if they are in the primary constructor.\n\nNote that you can also use Java’s `transient` keyword or Kotlin's `@Transient` annotation on these fields\nfor the same effect.\n\n### Default Values \u0026 Constructors\n\nWhen reading JSON that is missing a field, Moshi relies on the Java or Kotlin or Android runtime to assign\nthe field’s value. Which value it uses depends on whether the class has a no-arguments constructor.\n\nIf the class has a no-arguments constructor, Moshi will call that constructor and whatever value\nit assigns will be used. For example, because this class has a no-arguments constructor the `total`\nfield is initialized to `-1`.\n\nNote: This section only applies to Java reflections.\n\n```java\npublic final class BlackjackHand {\n  private int total = -1;\n  ...\n\n  private BlackjackHand() {\n  }\n\n  public BlackjackHand(Card hidden_card, List\u003cCard\u003e visible_cards) {\n    ...\n  }\n}\n```\n\nIf the class doesn’t have a no-arguments constructor, Moshi can’t assign the field’s default value,\n**even if it’s specified in the field declaration**. Instead, the field’s default is always `0` for\nnumbers, `false` for booleans, and `null` for references. In this example, the default value of\n`total` is `0`!\n\n\n```java\npublic final class BlackjackHand {\n  private int total = -1;\n  ...\n\n  public BlackjackHand(Card hidden_card, List\u003cCard\u003e visible_cards) {\n    ...\n  }\n}\n```\n\nThis is surprising and is a potential source of bugs! For this reason consider defining a\nno-arguments constructor in classes that you use with Moshi, using `@SuppressWarnings(\"unused\")` to\nprevent it from being inadvertently deleted later:\n\n\n```java\npublic final class BlackjackHand {\n  private int total = -1;\n  ...\n\n  @SuppressWarnings(\"unused\") // Moshi uses this!\n  private BlackjackHand() {\n  }\n\n  public BlackjackHand(Card hidden_card, List\u003cCard\u003e visible_cards) {\n    ...\n  }\n}\n```\n\n### Composing Adapters\n\nIn some situations Moshi's default Java-to-JSON conversion isn't sufficient. You can compose\nadapters to build upon the standard conversion.\n\nIn this example, we turn serialize nulls, then delegate to the built-in adapter:\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nclass TournamentWithNullsAdapter {\n  @ToJson void toJson(JsonWriter writer, Tournament tournament,\n      JsonAdapter\u003cTournament\u003e delegate) throws IOException {\n    boolean wasSerializeNulls = writer.getSerializeNulls();\n    writer.setSerializeNulls(true);\n    try {\n      delegate.toJson(writer, tournament);\n    } finally {\n      writer.setLenient(wasSerializeNulls);\n    }\n  }\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nclass TournamentWithNullsAdapter {\n  @ToJson fun toJson(writer: JsonWriter, tournament: Tournament?,\n    delegate: JsonAdapter\u003cTournament?\u003e) {\n    val wasSerializeNulls: Boolean = writer.getSerializeNulls()\n    writer.setSerializeNulls(true)\n    try {\n      delegate.toJson(writer, tournament)\n    } finally {\n      writer.setLenient(wasSerializeNulls)\n    }\n  }\n}\n```\n\u003c/details\u003e\n\n\nWhen we use this to serialize a tournament, nulls are written! But nulls elsewhere in our JSON\ndocument are skipped as usual.\n\nMoshi has a powerful composition system in its `JsonAdapter.Factory` interface. We can hook in to\nthe encoding and decoding process for any type, even without knowing about the types beforehand. In\nthis example, we customize types annotated `@AlwaysSerializeNulls`, which an annotation we create,\nnot built-in to Moshi:\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\n@Target(TYPE)\n@Retention(RUNTIME)\npublic @interface AlwaysSerializeNulls {}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\n@Target(TYPE)\n@Retention(RUNTIME)\nannotation class AlwaysSerializeNulls\n```\n\u003c/details\u003e\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\n@AlwaysSerializeNulls\nstatic class Car {\n  String make;\n  String model;\n  String color;\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\n@AlwaysSerializeNulls\nclass Car(\n  val make: String?,\n  val model: String?,\n  val color: String?\n)\n```\n\u003c/details\u003e\n\nEach `JsonAdapter.Factory` interface is invoked by `Moshi` when it needs to build an adapter for a\nuser's type. The factory either returns an adapter to use, or null if it doesn't apply to the\nrequested type. In our case we match all classes that have our annotation.\n\n\u003cdetails\u003e\n    \u003csummary\u003eJava\u003c/summary\u003e\n\n```java\nstatic class AlwaysSerializeNullsFactory implements JsonAdapter.Factory {\n  @Override public JsonAdapter\u003c?\u003e create(\n      Type type, Set\u003c? extends Annotation\u003e annotations, Moshi moshi) {\n    Class\u003c?\u003e rawType = Types.getRawType(type);\n    if (!rawType.isAnnotationPresent(AlwaysSerializeNulls.class)) {\n      return null;\n    }\n\n    JsonAdapter\u003cObject\u003e delegate = moshi.nextAdapter(this, type, annotations);\n    return delegate.serializeNulls();\n  }\n}\n```\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKotlin\u003c/summary\u003e\n\n```kotlin\nclass AlwaysSerializeNullsFactory : JsonAdapter.Factory {\n  override fun create(type: Type, annotations: Set\u003cAnnotation\u003e, moshi: Moshi): JsonAdapter\u003c*\u003e? {\n    val rawType: Class\u003c*\u003e = type.rawType\n    if (!rawType.isAnnotationPresent(AlwaysSerializeNulls::class.java)) {\n      return null\n    }\n    val delegate: JsonAdapter\u003cAny\u003e = moshi.nextAdapter(this, type, annotations)\n    return delegate.serializeNulls()\n  }\n}\n```\n\u003c/details\u003e\n\nAfter determining that it applies, the factory looks up Moshi's built-in adapter by calling\n`Moshi.nextAdapter()`. This is key to the composition mechanism: adapters delegate to each other!\nThe composition in this example is simple: it applies the `serializeNulls()` transform on the\ndelegate.\n\nComposing adapters can be very sophisticated:\n\n * An adapter could transform the input object before it is JSON-encoded. A string could be\n   trimmed or truncated; a value object could be simplified or normalized.\n\n * An adapter could repair the output object after it is JSON-decoded. It could fill-in missing\n   data or discard unwanted data.\n\n * The JSON could be given extra structure, such as wrapping values in objects or arrays.\n\nMoshi is itself built on the pattern of repeatedly composing adapters. For example, Moshi's built-in\nadapter for `List\u003cT\u003e` delegates to the adapter of `T`, and calls it repeatedly.\n\n### Precedence\n\nMoshi's composition mechanism tries to find the best adapter for each type. It starts with the first\nadapter or factory registered with `Moshi.Builder.add()`, and proceeds until it finds an adapter for\nthe target type.\n\nIf a type can be matched multiple adapters, the earliest one wins.\n\nTo register an adapter at the end of the list, use `Moshi.Builder.addLast()` instead. This is most\nuseful when registering general-purpose adapters, such as the `KotlinJsonAdapterFactory` below.\n\nKotlin\n------\n\nMoshi is a great JSON library for Kotlin. It understands Kotlin’s non-nullable types and default\nparameter values. When you use Kotlin with Moshi you may use reflection, codegen, or both.\n\n#### Reflection\n\nThe reflection adapter uses Kotlin’s reflection library to convert your Kotlin classes to and from\nJSON. Enable it by adding the `KotlinJsonAdapterFactory` to your `Moshi.Builder`:\n\n```kotlin\nval moshi = Moshi.Builder()\n    .addLast(KotlinJsonAdapterFactory())\n    .build()\n```\n\nMoshi’s adapters are ordered by precedence, so you should use `addLast()` with\n`KotlinJsonAdapterFactory`, and `add()` with your custom adapters.\n\nThe reflection adapter requires the following additional dependency:\n\n```xml\n\u003cdependency\u003e\n  \u003cgroupId\u003ecom.squareup.moshi\u003c/groupId\u003e\n  \u003cartifactId\u003emoshi-kotlin\u003c/artifactId\u003e\n  \u003cversion\u003e1.15.2\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n```kotlin\nimplementation(\"com.squareup.moshi:moshi-kotlin:1.15.2\")\n```\n\nNote that the reflection adapter transitively depends on the `kotlin-reflect` library which is a\n2.5 MiB .jar file.\n\n#### Codegen\n\nMoshi’s Kotlin codegen support can be used as a Kotlin SymbolProcessor ([KSP][ksp]).\nIt generates a small and fast adapter for each of your Kotlin classes at compile-time. Enable it by annotating\neach class that you want to encode as JSON:\n\n```kotlin\n@JsonClass(generateAdapter = true)\ndata class BlackjackHand(\n  val hidden_card: Card,\n  val visible_cards: List\u003cCard\u003e\n)\n```\n\nThe codegen adapter requires that your Kotlin types and their properties be either `internal` or\n`public` (this is Kotlin’s default visibility).\n\nKotlin codegen has no additional runtime dependency. You’ll need to enable kapt or KSP and then\nadd the following to your build to enable the annotation processor:\n\n\u003cdetails open\u003e\n    \u003csummary\u003eKSP\u003c/summary\u003e\n\n```kotlin\nplugins {\n  id(\"com.google.devtools.ksp\").version(\"1.6.10-1.0.4\") // Or latest version of KSP\n}\n\ndependencies {\n  ksp(\"com.squareup.moshi:moshi-kotlin-codegen:1.15.2\")\n}\n\n```\n\u003c/details\u003e\n\n#### Limitations\n\nIf your Kotlin class has a superclass, it must also be a Kotlin class. Neither reflection or codegen\nsupport Kotlin types with Java supertypes or Java types with Kotlin supertypes. If you need to\nconvert such classes to JSON you must create a custom type adapter.\n\nThe JSON encoding of Kotlin types is the same whether using reflection or codegen. Prefer codegen\nfor better performance and to avoid the `kotlin-reflect` dependency; prefer reflection to convert\nboth private and protected properties. If you have configured both, generated adapters will be used\non types that are annotated `@JsonClass(generateAdapter = true)`.\n\nDownload\n--------\n\nDownload [the latest JAR][dl] or depend via Maven:\n\n```xml\n\u003cdependency\u003e\n  \u003cgroupId\u003ecom.squareup.moshi\u003c/groupId\u003e\n  \u003cartifactId\u003emoshi\u003c/artifactId\u003e\n  \u003cversion\u003e1.15.2\u003c/version\u003e\n\u003c/dependency\u003e\n```\nor Gradle:\n```kotlin\nimplementation(\"com.squareup.moshi:moshi:1.15.2\")\n```\n\nSnapshots of the development version are available in [Sonatype's `snapshots` repository][snap].\n\n\nR8 / ProGuard\n--------\n\nMoshi 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.\n\n#### Enums\n\nAnnotate enums with `@JsonClass(generateAdapter = false)` to prevent them from being removed/obfuscated from your code by R8/ProGuard.\n\nLicense\n--------\n\n    Copyright 2015 Square, Inc.\n\n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n\n [dl]: https://search.maven.org/classic/remote_content?g=com.squareup.moshi\u0026a=moshi\u0026v=LATEST\n [snap]: https://oss.sonatype.org/content/repositories/snapshots/com/squareup/moshi/\n [okio]: https://github.com/square/okio/\n [okhttp]: https://github.com/square/okhttp/\n [gson]: https://github.com/google/gson/\n [javadoc]: https://square.github.io/moshi/1.x/moshi/\n [ksp]: https://github.com/google/ksp\n","funding_links":[],"categories":["III. Network and Integration","JSON","Libraries","[Programming]","Development setup","Kotlin","Projects","Java","项目","常用框架\\\u0026第三方库","HarmonyOS","Index","Android Kotlin Project Showcase","Built With 🛠"],"sub_categories":["8.  Json","[Programming] - [Java]","Libraries","JSON","Windows Manager"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsquare%2Fmoshi","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsquare%2Fmoshi","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsquare%2Fmoshi/lists"}