Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

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?

share|improve this question
8  
You're looking for a JSON parser. – SLaks Dec 26 '14 at 0:40
    
Trim the quotes and squarebrackets, split by comma. Done. – Thomas Junk Dec 26 '14 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. – David Dec 26 '14 at 0:47
    
@David yes, you are right: split by comma has to go first ;) – Thomas Junk Dec 26 '14 at 16:11

2 Answers 2

up vote 4 down vote accepted

I solved it using Gson.

Type listType = new TypeToken<List<String>>() {}.getType();
List<String> postData = new Gson().fromJson(stringThatLooksLikeArray, listType);
share|improve this answer
    
This is the only solution that pays proper attention to doublequotes when splitting the string. – dasblinkenlight Dec 26 '14 at 0:50
1  
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. – David Dec 26 '14 at 0:56

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.

share|improve this answer
2  
"Hi, hi" gets split up. – aioobe Dec 26 '14 at 0:54
    
@aioobe no, it doesn't – Bohemian Dec 26 '14 at 1:22
    
It did at the time I wrote the comment. Looks good now. (But you might want to trim the parts.) – aioobe Dec 26 '14 at 10:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.