在 kotlin 中检查 Json 类型

Checking Json type in kotlin

我有一个 json 对象,可以是 String 或 JsonArray。它取决于我从中获取数据的 API,但我不知道我得到了什么,所以我需要检查。

我尝试做的事情:

   val myData = optional.get("keyOfData")

    when(myData) {
        is JsonObject -> {
            when (mainCondition.asString) {
            //do something as string
            }
        }
        is JsonArray -> {
            myData.asJsonArray.forEach {
                when (it.asString) {
                    //do with each string
                }
            }


        }
    }

但是“myData”是 JsonPrimitive,所以它确实有效。我不想用 try/catch 签到。能否请您建议如何完成类型检查?

您可以尝试这样的操作(这是为了使用 Assertion.Builder 进行测试)。

使用 it.nodeType 可以检测 json 节点的类型。

infix fun Assertion.Builder<JsonNode>.isEqualTo(expected: String?): Assertion.Builder<JsonNode> {
    return assert("is a string with value, expected) {
        when (it.nodeType) {
            JsonNodeType.STRING -> {
                val textValue = it.textValue()
                if (expected == textValue) {
                    // Some output
                } else {
                    // Some output
                }
            }
            else -> // Some output
        }
    }