1

I have a jsonArray object like the "Input" below. I would like the "Output". Could you help me ?

Input :

"["a", "b", "c", "d"]"

Output :

["a", "b", "c", "d"]

//i need a simple list of string

I have found a solution but it's too complex for a simple conversion....

        val errorFields = jsonResponse.getJSONArray("my_array")
                .join(",")
                .replace("\"", "")
                .split(",")
diAz
  • 478
  • 4
  • 16
  • This seems like a duplicate of https://stackoverflow.com/questions/17037340/converting-jsonarray-to-arraylist But in Kotlin – Lucas Mendonca Oct 10 '19 at 16:23

3 Answers3

1

By manual parsing you can get a list of string from jsonArray by -

val list = ArrayList<String>()
repeat(jsonArray.length){
    list.add(jsonArray.getString(it))
}

If you are using parsing library gson than you can get a list of strings by -

val list = gson.fromJson(jsonArray.toString(), Array<String>::class.java)?.toList()
Naresh NK
  • 1,036
  • 1
  • 9
  • 16
0

You could do it like so:

    val stringList : MutableList<String> = arrayListOf()
    jsonArray?.let {
        for (i in 0 until it.length()) {
            stringList.add(jsonArray.getString(i))
    }
Squti
  • 4,171
  • 3
  • 10
  • 21
0

You can do this way in Koltin

var str = "[\"a\", \"b\", \"c\", \"d\"]" var items = Arrays.asList(str?.split("\\s*,\\s*")).flatten()

flatten is needed as it returns a list of lists.

Ranjeet
  • 393
  • 2
  • 10