Skip to content

Instantly share code, notes, and snippets.

@jameslmartin
Created July 11, 2014 18:30
Show Gist options
  • Save jameslmartin/5e27b176fcd943717b0b to your computer and use it in GitHub Desktop.
Save jameslmartin/5e27b176fcd943717b0b to your computer and use it in GitHub Desktop.
Neat little JSON parser, grabs outer level keys from a JSONObject that has been converted to a string with toString() and returns them in an ArrayList
/**
* getNames() - Returns ArrayList of Strings that are outer-most keys of a JSONObject that has been converted
* to a String with the toString() method (JSON4J)
* @author martinlj
* @param json - JSONObject that has been converted to a string with toString()
*/
private ArrayList<String> getNames(String json){
//Strip outer curly braces
json = json.substring(1,json.length()-1);
ArrayList<String> names = new ArrayList<String>();
String outerKey = "";
int curlyCount = 0;
int commaIndex = 0;
for(int i=0; i<json.length(); i++){
if(json.charAt(i) == ':' && curlyCount == 0){
outerKey = json.substring(commaIndex+1,i);
//Strip quotes if needed
if(outerKey.charAt(0)== '\"'){
outerKey = outerKey.substring(1);
}
if(outerKey.charAt(outerKey.length()-1) == '\"'){
outerKey = outerKey.substring(0,outerKey.length()-1);
}
//Add to ArrayList
names.add(outerKey);
}
else if(json.charAt(i) == '{'){
curlyCount++;
}
else if(json.charAt(i) == '}'){
curlyCount--;
}
else if(json.charAt(i) == ','){
commaIndex = i;
}
}
return names;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment