简体   繁体   English

如何将字符串转换为Java列表?

[英]How to convert a string to a java list?

I have a string like so: 我有一个像这样的字符串:

"[1,2,3,4,5,6,7,8,9]"

How can I turn it into List, could be list of int or list of strings: 如何将其转换为列表,可以是整数列表或字符串列表:

[1,2,3,4,5,6,7,8,9]

I tried using Gson: 我尝试使用Gson:

List list = new Gson().fromJson(string, List.class);

It gets me: 它让我:

[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]

I could convert the double to int but I'm sure there's a better way. 我可以将double转换为int,但是我确定有更好的方法。

Gson, by default, uses Double for any numeric value. 默认情况下,Gson将Double用作任何数值。 You need to specify that you want Integer 您需要指定要Integer

List<Integer> list = new Gson().fromJson(json, new TypeToken<List<Integer>>() {}.getType());
System.out.println(list);

prints 版画

[1, 2, 3, 4, 5, 6, 7, 8, 9]

A TypeToken is kind of a hack to get the generic type so that Gson knows what to use. TypeToken是一种获取通用类型的技巧 ,因此Gson知道使用什么。

In addition to Gson, you can do this: 除了Gson,您还可以执行以下操作:

String yourString = "[1,2,3,4,5,6,7,8,9]";
yourString = yourString.subString(1,yourString.length()-1) // get rid of '[' and ']'
List<String> list = new ArrayList<String>(Arrays.asList(yourString.split(",")));
String s = "[1,2,3,4]";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(s);
List<Integer> integers = new ArrayList<Integer>();
while (m.find()) {
    integers.add(Integer.parseInt(m.group()));
}
System.out.println(integers);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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