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(",")
1

3 Answers 3

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()
Sign up to request clarification or add additional context in comments.

1 Comment

i enjoy your solution with gson
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))
    }

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.