假设我正在使用gson在Kotlin数据类中对json进行序列化和反序列化。其中一个值是设置为"is"或“否”的字符串,另一个是设置为“开”或“关”的字符串。是的,这是可怕的做法,但让我们假设它不能更改。
在Kotlin中处理此问题的最佳方法是什么?
APIdata.json
{
"value" : "On",
"anotherValue" : "Yes"
}
APIdata.kt
data class APIdata (val value : String, val anotherValue: String)
为了获取和设置,我希望能够将它们都视为 bool(boolean) 值。
最佳答案
您可以使用映射函数和相应的构造函数,也可以定义get方法:
data class APIdata(val value: String, val anotherValue: String) {
fun mapToBoolean(string: String) =
when (string.toLowerCase()) {
"yes" -> true
"on" -> true
else -> false
}
constructor(value: Boolean, anotherValue: Boolean) :
this(if (value) "on" else "off", if (anotherValue) "yes" else "no")
fun getValue(): Boolean {
return mapToBoolean(value)
}
fun getAnotherValue(): Boolean {
return mapToBoolean(anotherValue)
}
}
在这种情况下,使用
data class
可能会产生误导,因为Kotlin编译器会假设hashCode
和equals
是value
而不是anotherValue
来生成String
和Boolean
。最好这样设计自己:class APIdata( val value: String, private val anotherValue: String) {
fun mapToBoolean(string: String) =
when (string.toLowerCase()) {
"yes" -> true
"on" -> true
else -> false
}
constructor(value: Boolean, anotherValue: Boolean) :
this(if (value) "on" else "off", if (anotherValue) "yes" else "no")
fun getValue(): Boolean {
return mapToBoolean(value)
}
fun getAnotherValue(): Boolean {
return mapToBoolean(anotherValue)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as APIdata
if (getValue() != other.getValue()) return false
if (getAnotherValue() != other.getAnotherValue()) return false
return true
}
override fun hashCode(): Int {
var result = getValue().hashCode()
result = 31 * result + getAnotherValue().hashCode()
return result
}
}
关于kotlin - 如何在Kotlin中将不良字符串作为伪 bool 值处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49615510/