Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm using a simple php API (that I wrote) that returns a JSON formatted string such as:

[["Air Fortress","5639"],["Altered Beast","6091"],["American Gladiators","6024"],["Bases Loaded II: Second Season","5975"],["Battle Tank","5944"]]

I now have a String that contains the JSON formatted string but need to convert it into two String arrays, one for name and one for id. Are there any quick paths to accomplishing this?

share|improve this question
Lots of parsers to choose from: stackoverflow.com/questions/338586/a-better-java-json-library – Eric Giguere Jan 27 '11 at 17:03
1  
aw! this ain't JSON. Where're da currley braces? ...and colons? – Nishant Jan 27 '11 at 17:07
For the record, none of these JSON libraries is going to work unless you actually emit proper JSON. I would start there... – Chris Thompson Jan 27 '11 at 17:16
Interesting. I was simply using php's json_encode function to output this. – madzilla Jan 27 '11 at 17:40
Perhaps the objects you are feeding it are wrong and this is the best it can do. Proper JSON would be: [{"Air Fortress":"5639"},{"Altered Beast":"6091"},{"American Gladiators":"6024"},{"Bases Loaded II: Second Season":"5975"},{"Battle Tank":"5944"}] – Andrew Jan 27 '11 at 20:39
show 1 more comment

1 Answer

up vote 2 down vote accepted

You can use the org.json library to convert your json string to a JSONArray which you can then iterate over.

For example:

String jsonString = "[[\"Air Fortress\",\"5639\"],[\"Altered Beast\",\"6091\"],[\"American Gladiators\",\"6024\"],[\"Bases Loaded II: Second Season\",\"5975\"],[\"Battle Tank\",\"5944\"]]";

List<String> names = new ArrayList<String>();
List<String> ids = new ArrayList<String>();
JSONArray array = new JSONArray(jsonString);
for(int i = 0 ; i < array.length(); i++){
    JSONArray subArray = (JSONArray)array.get(i);
    String name = (String)subArray.get(0);
    names.add(name);
    String id = (String)subArray.get(1);
    ids.add(id);
}

//to convert the lists to arrays
String[] nameArray = names.toArray(new String[0]);
String[] idArray = ids.toArray(new String[0]);

You can even use a regex to get the job done, although its much better to use a json library to parse json:

List<String> names = new ArrayList<String>();
List<String> ids = new ArrayList<String>();
Pattern p = Pattern.compile("\"(.*?)\",\"(.*?)\"") ;
Matcher m = p.matcher(s);
while(m.find()){
    names.add(m.group(1));
    ids.add(m.group(2));
}
share|improve this answer
This worked perfectly and without the use or an additional library. Thank you! – madzilla Jan 28 '11 at 16:03

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.