Kotlin converting JSONArray to ArrayList with extension functions

Convert string list from JSONArray to ArrayList

fun JSONArray.toArrayList(): ArrayList {
    val list = arrayListOf()
    for (i in 0 until this.length()) {
        list.add(this.getString(i))
    }

    return list
}

val messages = JSONArray("['aaa','bbb','ccc']")
messages.toArrayList()

Remove a string from JSONArray

fun JSONArray.remove(value: String) {
    for (i in 0 until this.length()) {
        if (value == this.get(i)) {
            this.remove(i)
            return
        }
    }
}
val messages = JSONArray("['aaa','bbb','ccc']")
messages.remove('bbb') // ['aaa','ccc']

Check if a string exist from a JSONArray

fun JSONArray.contains(value: String): Boolean {
    for (i in 0 until this.length()) {
        if (value == this.get(i)) {
            return true
        }
    }

    return false
}
val messages = JSONArray("['aaa','bbb','ccc']")
messages.contains('bbb') // true
messages.contains('ddd') // false

Search within Codexpedia

Custom Search

Search the entire web

Custom Search