From Newsgroup: comp.mobile.android
Jakub <
jak74@interia.pl> wrote or quoted:
How to split / convert this string into array at kotlin
["nick","first name","last name"]
Untested and generated text:
| To convert a JSON-formatted string representation of an array into an
| actual Kotlin List or Array, you need to parse the JSON rather than
| using a simple string split.
|
| Here are the two best ways to do this using standard Kotlin libraries.
|
| Option 1: Using kotlinx.serialization (Recommended)
|
| This is the official, type-safe Kotlin way to handle JSON parsing.
|
| import kotlinx.serialization.json.Json
|
| fun main() {
| val jsonString = """["nick","first name","last name"]"""
|
| // Parses directly into a List<String>
| val list: List<String> = Json.decodeFromString(jsonString)
|
| // Optional: Convert list to Typed Array if strictly needed
| val array: Array<String> = list.toTypedArray()
|
| println(list) // Prints: first name
| }
|
| Option 2: Using standard string manipulation (No Libraries)
|
| If your input string format is always simple and you cannot add
| external dependencies, you can clean up the brackets and split by
| commas.
|
| fun main() {
| val string = """["nick","first name","last name"]"""
|
| val array = string
| .trim('[', ']') // Removes the bounding brackets
| .split(",") // Splits by comma
| .map { it.trim('"') } // Removes the surrounding quotes from each element
| .toTypedArray() // Converts the resulting list to an array
|
| println(array) // Prints: first name
| }
--- Synchronet 3.22a-Linux NewsLink 1.2