Skip to content

Instantly share code, notes, and snippets.

@stefanmedack
Last active June 7, 2022 14:17
Show Gist options
  • Save stefanmedack/719fd8d905c6be982e1b4f807cbda3fa to your computer and use it in GitHub Desktop.
Save stefanmedack/719fd8d905c6be982e1b4f807cbda3fa to your computer and use it in GitHub Desktop.
Adapter for Moshi taking in a class definition and a default return value in case of a parsing error. Kotlin version of same-name-class from Moshi examples: https://github.com/square/moshi/blob/master/examples/src/main/java/com/squareup/moshi/recipes/DefaultOnDataMismatchAdapter.java
package com.ajnsnewmedia.kitchenstories.moshi.adapter
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import timber.log.Timber
import java.io.IOException
import java.lang.reflect.Type
class DefaultOnDataMismatchAdapter<T> private constructor(private val delegate: JsonAdapter<T>, private val defaultValue: T?) : JsonAdapter<T>() {
@Throws(IOException::class)
override fun fromJson(reader: JsonReader): T? {
return try {
delegate.fromJsonValue(reader.readJsonValue())
} catch (e: Exception) {
Timber.w("Wrongful content - could not parse delegate " + delegate.toString())
defaultValue
}
}
@Throws(IOException::class)
override fun toJson(writer: JsonWriter, value: T?) {
delegate.toJson(writer, value)
}
companion object {
@JvmStatic fun <T> newFactory(type: Class<T>, defaultValue: T?): JsonAdapter.Factory {
return object : JsonAdapter.Factory {
override fun create(requestedType: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*>? {
if (type != requestedType) {
return null
}
val delegate = moshi.nextAdapter<T>(this, type, annotations)
return DefaultOnDataMismatchAdapter(delegate, defaultValue)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment