moshi kotlin非构造函数属性未序列化

时间:2018-06-03 10:24:55

标签: android kotlin moshi

我有一个像这样定义的类:

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"))
}

1 个答案:

答案 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()
}