[英]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? 如何将其转换为String
的ArrayList
?
Use Arrays#asList
使用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. 当且仅当您始终会收到此格式的String
时,才应尝试上述操作。 Otherwise, use a proper JSON parser library like Jackson . 否则,请使用适当的JSON解析器库,例如Jackson 。
Method 1: Iterate through the array and put each element to arrayList on every iteration. 方法1:遍历数组,并在每次迭代时将每个元素放入arrayList。
Method 2: Use asList() method
方法2:使用asList() method
Example1: Using asList() method 示例1:使用asList()方法
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 Example2使用简单迭代
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 ('[',']') 如果您删除了前括号和后括号('[',']'),则可以使用简单的CSV分析器
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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.