2

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?

6
  • Lots of parsers to choose from: stackoverflow.com/questions/338586/a-better-java-json-library Commented Jan 27, 2011 at 17:03
  • 1
    aw! this ain't JSON. Where're da currley braces? ...and colons? Commented Jan 27, 2011 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... Commented Jan 27, 2011 at 17:16
  • Interesting. I was simply using php's json_encode function to output this. Commented Jan 27, 2011 at 17:40
  • 1
    Actually, proper JSON would probably look more like: [{"name":"Air Fortress","id":"5639"},{"name":"Altered Beast","id":"6091"},{"name":"American Gladiators","id":"6024"},{"name":"Bases Loaded II: Second Season","id":"5975"},{"name":"Battle Tank","id":"5944"}] Commented Jan 27, 2011 at 20:40

1 Answer 1

6

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

1 Comment

This worked perfectly and without the use or an additional library. Thank you!

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.