Encode String to UTF-8 in Kotlin
Solution 1
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.
Solution 2
You can try this String(data, Charsets.UTF_8)
Reference : https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/to-string.html
Solution 3
using kotlin function as
charset("UTF-8")
using from your data
String(response.data, charset("UTF-8"))
Solution 4
Kotlin 1.3.40 provides an experimental 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:
String response = response.data.decodeToString()
Note that using this function requires to opt in for the experimental stdlib API. You can learn more about the supported ways to make this opt-in here: https://kotlinlang.org/docs/reference/experimental.html
portfoliobuilder
I am a mobile app developer. Hit me up if you have any questions: [email protected]
Updated on July 29, 2020Comments
-
portfoliobuilder almost 4 years
Often times when dealing with json and responses you want to encode String to UTF-8 in java.
String response = new String(response.data, UTF); // java code
For Kotlin, how is this done? I converted my Java class and the result was
String response = String(response.data, UTF) // kotlin code
But this results in an error, because I believe the Kotlin String() method is different than what I am doing in Java. Is it as simple as using the toString()?
String response = response.data.toString() // kotlin code
How does the system know to use UTF-8, or is that just the default? This is just hypothetical, but what if I wanted to do something with String object and therefore used UTF-16? How can I change the encoding?
-
portfoliobuilder almost 5 yearsI see, simple. Kotlin makes things simpler seems like. Just need to learn more about the language. Thanks for your answer, I will try it.
-
Gavin almost 5 yearsByteArray.stringFromUtf8 seems to be only available for native code?
-
portfoliobuilder almost 5 yearsDo you think this is the better way to go? Presumably, this would mean that ByteArray,decodeToString() will be the new way to doing things and ByteArray.toString() may be deprecated (or not supported), right?
-
Shujat Munawar over 4 yearsThanks man, this should be accepted answer, Simple, easy and well defined Thanks again