iCodeLikeImDrunk
iCodeLikeImDrunk

Reputation: 17806

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.

Upvotes: 1

Views: 104

Answers (3)

mishadoff
mishadoff

Reputation: 10789

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

Upvotes: 1

Paul Lo
Paul Lo

Reputation: 6138

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(",")));

Upvotes: 2

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

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.

Upvotes: 5

Related Questions