Encode String to UTF-8 in Kotlin
Kotlin has an overload of ByteArray.toString
accepting a Charset
. All you need to do is use it: array.toString(charset)
.
I cannot find a section in the documentation specifying that ByteArray.toString()
does the right thing, as it doesn't in Java and that behavior probably is preserved in Kotlin. I would guess it does the wrong thing. I recommend using toString(charset)
explicitly.
using kotlin function as
charset("UTF-8")
using from your data
String(response.data, charset("UTF-8"))
Kotlin 1.4 provides a common ByteArray.decodeToString
function.
It takes a ByteArray
containing bytes of string encoded with utf8 encoding and decodes it to kotlin String
. So you can use it like:
val response: String = response.data.decodeToString()
You can try this String(data, Charsets.UTF_8)
Reference : https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/to-string.html