David
David

Reputation: 7486

Java convert String that looks like an Array into a String Array or String ArrayList

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?

Upvotes: 4

Views: 654

Answers (2)

Bohemian
Bohemian

Reputation: 425328

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.

Upvotes: 1

David
David

Reputation: 7486

I solved it using Gson.

Type listType = new TypeToken<List<String>>() {}.getType();
List<String> postData = new Gson().fromJson(stringThatLooksLikeArray, listType);

Upvotes: 4

Related Questions