I am using Moshi with Kotlin. According to the README, an custom TypeAdapter may like this:
class CardAdapter {
@ToJson String toJson(Card card) {
return card.rank + card.suit.name().substring(0, 1);
}
@FromJson Card fromJson(String card) {
return //...
}
}
It receive an Object or String, transform to another. But I made an Adapter like this:
class ConfigAdapter{
@ToJson
fun toJson(writer: JsonWriter, value: WfBaseConfig?) {
val moshi = Moshi.Builder().build()
when (value) {
is BoolConfig -> moshi.adapter(BoolConfig::class.java).toJson(writer, value)
// Other types ...
else -> throw
IllegalArgumentException("Unknown wf config type: ${value::class.java.simpleName}")
}
}
@FromJson
fun fromJson(reader: JsonReader): BaseConfig? {
var type = ""
val copy = reader.peekJson()
copy.readObject {
when (copy.selectName(JsonReader.Options.of("type"))) {
0 -> type = copy.nextString()
else -> copy.skipNameAndValue()
}
}
val moshi = Moshi.Builder().build()
return when (type) {
"boole" -> moshi.adapter(BoolConfig::class.java).fromJson(reader)
// Other operations...
else -> {
e("Unknown config type: $type")
null
}
}
}
private fun JsonReader.skipNameAndValue() {
skipName()
skipValue()
}
}
Original JSON format:
[
{
"id": "show_weather",
"type": "boole",
"title_en": "Show Weather",
"def": false
},
{
"id": "text_size",
"type": "list",
"title_en": "Text Size",
"item_type": "text",
"def": 1,
"data": [{
"id": 0,
"title_en": "Large",
},
{
"id": 1,
"title_en": "Middle",
},
{
"id": 2,
"title_en": "Small",
}
]
}
]
Explanation: The format of each object is determined by type
, if it was list
, format of data
will be determined by item_type
.
Use it:
val listType = Types.newParameterizedType(List::class.java, BaseConfig::class.java)
val moshi = Moshi.Builder().add(ConfigAdapter()).build()
return moshi.adapter<List<BaseConfig>>(listType).fromJson(conf)
It works well too. The logic of parsing is not important. I just can't work out what type or parameters can we use in toJson()
or fromJson()
. I failed to find any documnets about that.
By the way, these parameters were generated by
JsonAdapter<T>
, but I remove the 'extent' at last because it causeUnable to resolve Lcom/squareup/moshi/JsonAdapter; annotation class 7823
warning logcat outputing. I am also very confused about when should I extendJsonAdapter
class or just ues@ToJson
/@FromJson
annotations.
Any explanation will be appreciated.