4

I have a String that looks like an Array:

["944", "The name", "Hi, hi", 1, 6, 0, false, "the date"]

NOTE: The above is wrapped in ", like a String would be. So the integers and boolean are in this String and those like "944" are also in the String, a String in a String if you will.

How do I take that and make it a Java String Array or ArrayList of Strings?

4
  • 8
    You're looking for a JSON parser. Commented Dec 26, 2014 at 0:40
  • Trim the quotes and squarebrackets, split by comma. Done. Commented Dec 26, 2014 at 0:45
  • 3
    @ThomasJunk, That wouldn't work. In the example above, That would split up the 3rd element, "Hi, hi". But yes, I forgot I have Gson in this project. Got it done. Commented Dec 26, 2014 at 0:47
  • @David yes, you are right: split by comma has to go first ;) Commented Dec 26, 2014 at 16:11

2 Answers 2

4

I solved it using Gson.

Type listType = new TypeToken<List<String>>() {}.getType();
List<String> postData = new Gson().fromJson(stringThatLooksLikeArray, listType);
Sign up to request clarification or add additional context in comments.

2 Comments

This is the only solution that pays proper attention to doublequotes when splitting the string.
I figure most running into what I ran into are doing some form of data transfer (most likely through JSON), so using Gson in any type of project like that offers these great short solutions.
1

Trim the head and tail of non-data then split:

String[] parts = str.replaceAll("^\\[|\\]$", "").split(",(?=(([^\"]*\"){2})*[^\"]*$)");

The look ahead assets that the comma being split on is not within a quote pair.

3 Comments

"Hi, hi" gets split up.
@aioobe no, it doesn't
It did at the time I wrote the comment. Looks good now. (But you might want to trim the parts.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.