Java 如何将带方括号的json字符串转换为列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18190001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert json String with Square brackets to List?
提问by Prateek
I have the following string : ["LankaBell","BillDesk"]
我有以下字符串: ["LankaBell","BillDesk"]
How can i convert it to Java List Object using using json-lib-2.2.3-jdk15.jar\net\sf\json
library ?
如何使用json-lib-2.2.3-jdk15.jar\net\sf\json
库将其转换为 Java 列表对象?
EDIT : If not possible using this library then solution using other libraries is also appreciated.
编辑:如果不可能使用这个库,那么使用其他库的解决方案也值得赞赏。
采纳答案by Yurii Shylov
Using the json-lib:
使用 json-lib:
String source = "[\"LankaBell\",\"BillDesk\"]";
List<String> list = new ArrayList<>();
list = JSONArray.toList(JSONArray.fromObject(source), new Object(), new JsonConfig());
(Actually you can use just JSONArray.toList(JSONArray.fromObject(source))
but it is deprecated)
(实际上你可以使用 justJSONArray.toList(JSONArray.fromObject(source))
但它已被弃用)
Another non-deprecated solution:
另一个未弃用的解决方案:
list = (List<String>) JSONArray.toCollection(JSONArray.fromObject(source))
回答by Brinnis
String string = "[\"LankaBell\",\"BillDesk\"]";
//Remove square brackets
string = string.substring(1, string.length()-1);
//Remove qutation marks
string.replaceAll("\"", "");
//turn into array
String[] array = string.split(",");
//Turn into list
List<String> list = Arrays.asList(array);
System.out.println(list);
回答by merfanzo
Object[] objs = "[\"Lankabell\", \"BillDesk\"]".replaceAll("\[|\]|\"","").split(",");
回答by superEb
回答by daveloyall
String input = "[\"LankaBell\",\"BillDesk\"]";
// net.sf.json.JSONArray
JSONArray jsonArray = JSONArray.fromObject(input);
List<String> list = new ArrayList<String>();
for (Object o : jsonArray) {
list.add((String) o);
}
log.debug(list);