Home > Back-end >  How to convert string which have array and string elements inside it, to fetch each element from the
How to convert string which have array and string elements inside it, to fetch each element from the

Time:09-23

My output looks like this :

["Floor 0","Floor 1","Floor 2"]

It comes as a string. But I want to fetch each element of this array. How can I do this using Kotlin ?

CodePudding user response:

Just use regular expressions to create a match for each CharSequence between the double quotes. As you want to use only the values between the quotes, you can extract the first index group values. The following code snippet does what you are asking for in Kotlin:

val str = "[\"Floor 0\",\"Floor 1\",\"Floor 2\"]"

val pattern = Regex( "\"(.*?)\"")

val fetched_elements = pattern.findAll(str).map {
    it.groupValues[1]
}.toList()

// creates the list: [Floor 0, Floor 1, Floor 2]

Use also this RegExr example to explore this in detail with explanation.

CodePudding user response:

implement this library Gson

you can use it like this

val text = "[\"Floor 0\",\"Floor 1\",\"Floor 2\"]"
val array = Gson().fromJson(text, ArrayList::class.java)
array.forEach {
      Log.e(TAG, "onCreate: it $it")
}

CodePudding user response:

If your internal strings aren't allowed to have commas, you could do it with a split function to convert it into a list:

var lst = str.replace("\"", "").split(",")

If your internal strings can have trailing whitespace, this would be better:

var lst = str.replace("\"", "").split(",").map { it.trim() }

In the above code lines, the replace function removes the quotes surrounding each internal string; the split separates the string at each comma; and the trim function removes any surrounding whitespace characters.

If your internal strings can contain commas, you're better off learning about and using regular expressions as mentioned in another answer.

  • Related