SalomonBrys / Kotson

Kotlin bindings for JSON manipulation via Gson
MIT License
709 stars 37 forks source link

isJsonString, isJsonNumber, isJsonBoolean; rather than simply isJsonPrimitive #42

Closed patarapolw closed 5 years ago

patarapolw commented 5 years ago

I also find that

@Test fun testJsonString() {
    val x = gson.fromJson<JsonArray>("""["a", 1.1, null]""")
    println(x[0].asString)  // Passed
    println(x[1].asString)  // Passed
    println(x[2].asString)  // Failed
}

@Test fun testJsonNumber() {
    val x = gson.fromJson<JsonArray>("""[1.1, "a", null]""")
    println(x[0].asDouble)  // Passed
    println(x[1].asDouble)  // Failed
    println(x[2].asDouble)  // Failed
}

I would be convenient if I don't have to test out how your library works...

Actually, I have got it, but I don't know how fragile it is.

fun JsonElement.asValue(): Any {
    return try {
        asDouble
    } catch (e: Exception) {
        try {
            val s = asString
            if (setOf("true", "false").contains(s)) {
                asBoolean
            } else s
        } catch (e: Exception) {
            this
        }
    }
}

To get the type, use .javaClass

class java.lang.String
class java.lang.Double
class com.google.gson.JsonNull
class java.lang.Boolean
class com.google.gson.JsonArray
class com.google.gson.JsonObject

Also, as a by-product

operator fun JsonElement.compareTo(b: JsonElement): Int {
    val m = asValue()
    val n = b.asValue()
    return if (m.javaClass == n.javaClass) {
        when(m) {
            is String -> m.compareTo(n as String)
            is Double -> m.compareTo(n as Double)
            else -> 0
        }
    } else 0
}
patarapolw commented 5 years ago

I have found the options. https://stackoverflow.com/questions/20624042/how-to-get-json-element-type-with-gson

JsonElement.asJsonPrimitive.isString
JsonElement.asJsonPrimitive.isNumber
JsonElement.asJsonPrimitive.isBoolean