How to convert a list<String> to string with prefix and postfix in kotlin

Mary Jane :

How can I convert a list of numbers to a string which could be used in JSON, with Kotlin in Android?

I used this could but this doesn't work:

l.toTypedArray().contentDeepToString()

input:

l: List<String> =[102,103]

output:

s:String = "["102","103"]"

Any help would be appreciated.

deHaar :

You can use joinToString like this:

fun main(args: Array<String>) {
    var l: List<String> = listOf("102" ,"103")
    return this.joinToString(prefix = "[\"", postfix = "\"]", separator = "\",\"")
}

The output looks like the desired one:

["102","103"]

For more information, read the documentation of joinToString.

You have the possibility of making this an extension function of List<String> in order to reduce code redundancy, if you need it more than once in your code:

// extend List<String> by a new method that creates your quoted String from the items
fun List<String>.toQuotedString(): String {
    return this.joinToString(prefix = "[\"", postfix = "\"]", separator = "\",\"")
}

fun main(args: Array<String>) {
    var l: List<String> = listOf("102" ,"103")
    println(l.toQuotedString())  // you can just use this method in your code
}

Addition
If you want it for a list of real numbers (your and my examples are using a List<String>), you can just do the same for a List<Int>:

fun List<Int>.toQuotedString(): String {
    return this.joinToString(prefix = "[\"", postfix = "\"]", separator = "\",\"")
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=32961&siteId=1