Dim
Dim

Reputation: 4827

Checking Json type in kotlin

I have an json object that can be String or JsonArray. Its depending on the API which I get the data from, but I dont know what I am getting so I need to check.

What I tried to do:

   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
                }
            }


        }
    }

But the "myData" is JsonPrimitive, so it does work. I do not wish to check in with try/catch. Can you please suggest how to accomplish the checking of type?

Upvotes: 0

Views: 1413

Answers (1)

nicowi
nicowi

Reputation: 472

You could try something like this (this is for testing with Assertion.Builder).

with it.nodeType you can detect the type of the json node.

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
        }
    }

Upvotes: 1

Related Questions