Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

kotlin/java how to convert string array to array?

I have an API that returns this type of data

{
"images":"[image1.png,image2.png,image3.png]"
}

how do you convert images string to array?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to get the string from the json object using jsonObject.getString("images") & then remove [] brackets. Then you need to use split on that string using , delimiter.

Java Code:

private String[] convertStringToArray(String s) {
        s = s.replaceAll("\\[", "");
        s = s.replaceAll("]", "");
        return s.split(",");
    }

Usage:

 try {
            JSONObject jsonObject = new JSONObject(response);
            String images = jsonObject.getString("images");
            String[] a = convertStringToArray(images);
            Log.d("MG-array", a.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

Kotlin:

private fun convertStringToArray(s: String): Array<String> {
        var varString = s
        varString = varString.replace("\\[".toRegex(), "")
        varString = varString.replace("]".toRegex(), "")
        return varString.split(",").toTypedArray()
    }

Usage:

try {
            val jsonObject = JSONObject(response)
            val images = jsonObject.getString("images")
            val a = convertStringToArray(images)
            Log.d("MG-array", a.toString())
        } catch (e: JSONException) {
            e.printStackTrace()
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading