Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Stringified array to ArrayList in Android

Tags:

java

android

I am getting this from server

"[\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]"

The above text is not an array, but a string returned from server.

I want to convert this in an ArrayList

Is there a way to convert it?

like image 245
Pawanpreet Singh Avatar asked Feb 05 '23 08:02

Pawanpreet Singh


2 Answers

There is no good idea to manually parse that string. You should use a library that parses JSON strings for you. Anyhow the given string is not a valid JSON string and like others have mentioned you should request JSON formatted data from the server.

If your server only returns like this and you need to manually parse then this would be a solution. Not a very good one, but it does the job.

public static void main(String[] args) {
    List<String> words = new ArrayList<>();
    String string = "[\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]";

    String withoutBrackets = string.replaceAll("[\\[\\](){}]", ""); // Remove all the brackets
    for (String word : withoutBrackets.split(",")) {
        String singleWord = word.replaceAll("\"", "");
        words.add(singleWord);
    }

    System.out.println(words);
}
like image 114
Andrei Olar Avatar answered Feb 15 '23 12:02

Andrei Olar


Can be done using separator, where s is String:

List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
like image 43
Gagan Sethi Avatar answered Feb 15 '23 12:02

Gagan Sethi