我有一个像这样定义的类:
data class Medicalnfo(
@Json(name = "allergies") val allergies: List<Allergy>? = null
): ProfileModel(){
@Json(name = "has_allergies") val hasAllergies: Boolean = allergies != null && allergies.isNotEmpty()
}
问题是 Moshi 生成的json序列化中不包含hasAllergies
。如何实现这一目标?
这是测试
@Test
fun medicalInfoJsonContainsFlags(){
val adapter = moshi.adapter(Medicalnfo::class.java)
val jsonStr = adapter.toJson(Medicalnfo(allergies = listOf())) //value is {"allergies":[]}
assert(jsonStr.contains("has_allergies"))
}
答案 0 :(得分:1)
如果您将 hasAllergies
设为 var 它将起作用
data class Medicalnfo(
@Json(name = "allergies") val allergies: List<Allergy>? = null
): ProfileModel(){
@Json(name = "has_allergies") var hasAllergies: Boolean = allergies != null && allergies.isNotEmpty()
}