学习Moshi
vs Gson
Gson的仓库介绍:Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
Gson专门用于Java。
Moshi的介绍:Moshi is a modern JSON library for Android, Java and Kotlin. It makes it easy to parse JSON into Java and Kotlin classes.
在开始学习之前,有理由推测 Moshi针对Kotlin做了一些提升,可以做到Gson对Kotlin所做不到的功能。
依赖
1 | // kts |
反射和codegen必须使用其一或都使用。不然会报错。
- 使用反射添加
KotlinJsonAdapterFactory
- 使用codegen在类添加
@JsonClass(generateAdapter = true)
基本使用
基本代码
1 | data class BlackjackHand( |
from json
1 | // from json |
to json
1 | // to json |
parse array
1 |
|
报错规则
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.
自定义字段名
1 | class Player { |
忽略字段
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)
.
1 | class BlackjackHand(...) { |
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.
自定义适配器
https://github.com/square/moshi#custom-type-adapters
https://github.com/square/moshi#alternate-type-adapters-with-jsonqualifier
Retrofit2 Gson迁移至Moshi
如果没有自定义适配器和自定义字段名,直接更改就好
1 | addConverterFactory(MoshiConverterFactory.create()) |