Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode String to UTF-8 in Kotlin

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?

like image 267
portfoliobuilder Avatar asked Jun 20 '19 17:06

portfoliobuilder


2 Answers

You can try this String(data, Charsets.UTF_8)

Reference : https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/to-string.html

like image 153
Sagar Devanga Avatar answered Oct 16 '22 04:10

Sagar Devanga


using kotlin function as

charset("UTF-8")

using from your data

 String(response.data, charset("UTF-8"))
like image 39
Gopi Cg Avatar answered Oct 16 '22 04:10

Gopi Cg