简体   繁体   中英

Convert a String into an array List Java

I have a String like this:

["http://www.ebuy.al/Images/dsc/17470_500_400.jpg", "http://www.ebuy.al/Images/dsc/17471_500_400.jpg"]

How can I convert it into an ArrayList of String s?

Use Arrays#asList

String[] stringArray = { "http://www.ebuy.al/Images/dsc/17470_500_400.jpg", "http://www.ebuy.al/Images/dsc/17471_500_400.jpg"}
List<String> stringList = Arrays.asList(stringArray);

In case your string contains braces [] and double quotes "" , then you should parse the string manually first.

String yourString = "[\"http://www.ebuy.al/Images/dsc/17470_500_400.jpg\", \"http://www.ebuy.al/Images/dsc/17471_500_400.jpg\"]";
String[] stringArray = yourString
    .substring(1, yourString.length() - 2)
    .replace('"', '\0')
    .split(",\\s+");
List<String> stringList = Arrays.asList(stringArray);

Try the above if and only if you will always receive your String in this format. Otherwise, use a proper JSON parser library like Jackson .

Method 1: Iterate through the array and put each element to arrayList on every iteration.

Method 2: Use asList() method

Example1: Using asList() method

String[] urStringArray = { "http://www.ebuy.al/Images/dsc/17470_500_400.jpg", "http://www.ebuy.al/Images/dsc/17471_500_400.jpg"}
List<String> newList = Arrays.asList(urStringArray);

Example2 Using simple iteration

List<String> newList = new ArrayList<String>();
for(String aString:urStringArray){
newList.add(aString);
}

You can use simple CSV parser if you remove the first and last brackets ('[',']')

Something like this:

List<String> items = Arrays.asList(str.split("\\s*,\\s*"));

This would be more appropriate

String jsonArr = "[\"http://www.ebuy.al/Images/dsc/17470_500_400.jpg\", 
                   \"http://www.ebuy.al/Images/dsc/17471_500_400.jpg\"]";
List<String> listFromJsonArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonArr);
for(int i =0 ;i<jsonArray.length();i++){
      listFromJsonArray.add(jsonArray.get(i).toString());
}

And don't forget to add json library

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM