kotlin - 如何在Kotlin中将不良字符串作为伪 bool 值处理?

标签 kotlin gson

假设我正在使用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编译器会假设hashCodeequalsvalue而不是anotherValue来生成StringBoolean。最好这样设计自己:
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/

相关文章:

gradle - 找不到 org.jetbrains.kotlinx :kotlinx-html:0. 6.4

java - 使用嵌套类映射 Json 字符串

java - 如何测试响应实体的 Spring mvc Controller 测试?

scala - 在 Scala 中使用 Gson 序列化/反序列化案例对象

java - 无法使用 Jackson 将 JSON HTTP 响应转换为 Java 对象

java - 改造: gson stackoverflow

android - 重复类 androidx.appcompat :appcompat

java - 在 Kotlin 中安全转换为泛型类型时出现异常

kotlin - 为什么在 Kotlin 中 var i 以 0 开头?

multithreading - Kotlin 协程多线程调度器和局部变量的线程安全