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.

6
  • 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. Commented Jan 16, 2019 at 14:32
  • sorry, the "array" is a string itself Commented Jan 16, 2019 at 14:35
  • @Thomas it is similar to JSON, but it is not JSON. Commented Jan 16, 2019 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. Commented Jan 16, 2019 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. Commented Jan 16, 2019 at 14:37

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.