这是我的模型课
data class Article(
val id: Int? = 0,
val is_local: Boolean? = false,
val comments: List<Comment?>? = listOf())
这是json
{
"id": 33,
"is_local": "true",
"comments":
[
{ "url": "aaa" },
{ "url": "bbb" },
{ "url": "ccc" )
]
}
我正在使用此自定义适配器返回默认值以防解析错误,例如我的情况是is_local字段
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)
}
}
}
}
}
并且我的测试失败并且布尔值不为假我已将上述适配器添加到 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
}
但是当我将模型类中 is_local 字段的数据类型更改为不可为空时,它可以工作