假设我正在使用gson在Kotlin数据类中对json进行序列化和反序列化。值之一是设置为“是”或“否”的字符串,而另一个值是设置为“开”或“关”的字符串。是的,这是可怕的做法,但让我们假定它不能更改。
在Kotlin中处理此问题的最佳方法是什么?
APIdata.json
{
"value" : "On",
"anotherValue" : "Yes"
}
APIdata.kt
data class APIdata (val value : String, val anotherValue: String)
为了获得和设置,我希望能够将它们都视为布尔值。
您可以使用映射函数和相应的构造函数,也可以定义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
能够误导,因为科特林编译器生成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
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句