1

I have a Java project witch consults an API which returns a String like:

"['test1', 'test2', 'test3']" // the array is a string

So basically an array object parsed to a String. I would like to know the best way to convert it to a real Java List.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
gog
  • 11,788
  • 23
  • 67
  • 129
  • 3
    Since that string looks like Json I suggest using a Json parser. There are a lot of libraries out there that you could use. – Thomas Jan 16 '19 at 14:32
  • sorry, the "array" is a string itself – gog Jan 16 '19 at 14:35
  • @Thomas it is similar to JSON, but it is not JSON. – Henry Jan 16 '19 at 14:35
  • JSON requires double quotes, so the single quotes would first have to be replaced. You'd need to be sure your values never contain any actual double quotes, though. – TiiJ7 Jan 16 '19 at 14:36
  • 1
    There is not enough information here to make a recommendation. What you have is an example, and you need a *definition*. Are the substrings always between single quotes? Is there allowance for empty strings, or empty arrays? Are the elements always strings? Are there escape characters to process? This are just the questions I came up with off the top of my head, no doubt if I spent 5 minutes or longer I could come up with more. You need a definition before you can decide. I am assuming you have no control over what is returned from the API, so you have to know how they've defined it. – arcy Jan 16 '19 at 14:37
  • @Henry, granted it's not in the standard definition of Json but almost all Json parsers I know of support single quotes for strings and thus could be considered a defacto standard. Even if not, I wrote "it looks like Json" not "it is Json" ;D – Thomas Jan 16 '19 at 14:40

1 Answers1

5

['test1', 'test2', 'test3'] is a JSON array so it can be parsed with Gson or Jackson. Although JSON usually mandates using double quotes around String values, Gson will still parse single quotes:

String json = "['test1', 'test2', 'test3']";
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> list = new Gson().fromJson(json, listType);
System.out.println(list); // [test1, test2, test3]

Alternatively you could use a regular expression. Assuming that values can't contain escaped apostrophe \' symbol:

String text = "['test1', 'test2', 'test3']";
Pattern pattern = Pattern.compile("'([^']+)'");
Matcher matcher = pattern.matcher(text);
List<String> list = new ArrayList<>();
while (matcher.find()) {
    list.add(matcher.group(1));
}
System.out.println(list); // [test1, test2, test3]
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111