Here is my model class
data class Article(
val id: Int? = 0,
val is_local: Boolean? = false,
val comments: List<Comment?>? = listOf())
and here is json
{
"id": 33,
"is_local": "true",
"comments":
[
{ "url": "aaa" },
{ "url": "bbb" },
{ "url": "ccc" )
]
}
i am using this custom Adapter to return default value in case of parsing error like in my case is is_local field
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? =
try {
delegate.fromJsonValue(reader.readJsonValue())
} catch (e: Exception) {
println("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)
}
}
}
}
}
and my test fail and boolean value is not false i have added the above adapter to moshi
@Before
fun createService() {
val moshi = Moshi.Builder()
.add(DefaultOnDataMismatchAdapter
.newFactory(Boolean::class.java,false))
.add(KotlinJsonAdapterFactory())
.build()
val retrofit = Retrofit.Builder()
.baseUrl(mockWebServer.url("/"))
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
service = retrofit.create(ApiStores::class.java)
}
@Test
fun getBooleanParsingError() {
enqueueResponse(case1)
val article = service.getArticle().execute()
assert(article.body()!!).isNotNull()
assert(article.body()!!.is_local).isEqualTo(false) // test fail here
}
but when i change the datatype of is_local field in the model class to not nullable it works