如何在Kotlin中将不良字符串作为伪布尔值处理?

极地声音

假设我正在使用gson在Kotlin数据类中对json进行序列化和反序列化。值之一是设置为“是”或“否”的字符串,而另一个值是设置为“开”或“关”的字符串。是的,这是可怕的做法,但让我们假定它不能更改。

在Kotlin中处理此问题的最佳方法是什么?

APIdata.json

{
   "value" : "On",
   "anotherValue" : "Yes"
}

APIdata.kt

data class APIdata (val value : String, val anotherValue: String)

为了获得和设置,我希望能够将它们都视为布尔值。

Leonardkraemer

您可以使用映射函数和相应的构造函数,也可以定义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能够误导,因为科特林编译器生成hashCodeequals假设valueanotherValueString而非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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Java中将字符串值转换为布尔值

如何在JavaScript中将字符串转换为布尔值?

如何在Go中将布尔值转换为字符串?

如何在Spring Boot Rest响应中将布尔值序列化为字符串?

如何在Matlab中将字符串变量转换为布尔值?

如何在Python中将布尔值连接到字符串?

如何在Python中将布尔值连接到字符串?

如何在JavaScript中将字符串转换为布尔值?

如何在ASP.NET中将Local用作布尔值的整数或字符串?

如何在lua中将字符串转换为布尔值

如何在MongoDB中将字符串转换为布尔值?

如何在 JavaScript 中将字符串转换为布尔值

如何在winform datagrid单元格中将布尔值转换和显示为字符串值

在JS中将“字符串”或布尔值作为参数传递是不好的做法吗?

在Kotlin中将“是”或“否”字符串转换为布尔值

如何在打字稿Angular 4中将字符串转换为布尔值

如何在变量中使用0作为字符串而不是||中的布尔值 手术?

在DataFrame中将布尔值转换为字符串

在PHP中将字符串解析为布尔值

获取布尔值作为字符串

字符串值如何用作布尔值

在PostgreSQL中,如何在jsonb键上返回布尔值而不是字符串?

如何在python JSON字符串处转义true / false布尔值

如何在查询绑定时将布尔值转换为字符串?

如何在Java中检查给定的字符串是否为布尔值?

如何在 Pandas 中将不需要的字符串值转换为 NaN

在WHERE子句中使用字符串值作为布尔值

如何在Jasper Studio中使用MySQL查询从布尔值获取字符串值

如何在模型中使用布尔值来包装数据库中的字符串值?