简体   繁体   中英

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:

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.

Gson, by default, uses Double for any numeric value. You need to specify that you want 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.

In addition to Gson, you can do this:

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);

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