That’s the mistakemoshi
Let you write a custom Adapter,
No JsonAdapter for class java.util.ArrayList.you should probably use List instead of ArrayList (Moshi only supports the collection interfaces by default) or else register a custom JsonAdapter.
java.lang.IllegalArgumentException: No JsonAdapter for class java.util.ArrayList.you should probably use List instead of ArrayList (Moshi only supports the collection interfaces by default) or else register a custom JsonAdapter.
Copy the code
The solution
Read the code below for yourself. Moshi is killing people these days.
abstract class MoshiArrayListJsonAdapter<C : MutableCollection<T>? .T> private constructor(
private val elementAdapter: JsonAdapter<T>
) :
JsonAdapter<C>() {
abstract fun newCollection(a): C
@Throws(IOException::class)
override fun fromJson(reader: JsonReader): C {
val result = newCollection()
reader.beginArray()
while(reader.hasNext()) { result? .add(elementAdapter.fromJson(reader)!!) } reader.endArray()return result
}
@Throws(IOException::class)
override fun toJson(writer: JsonWriter, value: C?). {
writer.beginArray()
for (element in value!!) {
elementAdapter.toJson(writer, element)
}
writer.endArray()
}
override fun toString(a): String {
return "$elementAdapter.collection()"
}
companion object {
val FACTORY = Factory { type, annotations, moshi ->
val rawType = Types.getRawType(type)
if (annotations.isNotEmpty()) return@Factory null
if (rawType == ArrayList::class.java) {
return@Factory newArrayListAdapter<Any>(
type,
moshi
).nullSafe()
}
null
}
private fun <T> newArrayListAdapter(
type: Type,
moshi: Moshi
): JsonAdapter<MutableCollection<T>> {
val elementType =
Types.collectionElementType(
type,
MutableCollection::class.java
)
val elementAdapter: JsonAdapter<T> = moshi.adapter(elementType)
return object :
MoshiArrayListJsonAdapter<MutableCollection<T>, T>(elementAdapter) {
override fun newCollection(a): MutableCollection<T> {
return ArrayList()
}
}
}
}
}
Copy the code
usage
I didn’t want to write it but I was afraid someone would scold me for not writing the whole code
Moshi.Builder()
.add(MoshiArrayListJsonAdapter.FACTORY)
.build()
Copy the code