Skip to content

Instantly share code, notes, and snippets.

@natanavra
Created October 11, 2015 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natanavra/2f50a65d1f1c7c87de57 to your computer and use it in GitHub Desktop.
Save natanavra/2f50a65d1f1c7c87de57 to your computer and use it in GitHub Desktop.
public static Object drillJSONObject(JSONObject obj, String path) throws JSONException {
if(path == null) {
return null;
} else if(path.length() == 0) {
return null;
}
Object jumper = obj;
String[] components = path.split("\\."); //Dots specifically not regex any char.
for(String component : components) {
if(!(jumper instanceof JSONObject) && !(jumper instanceof JSONArray)) {
jumper = null;
break;
}
int openBracketIndex = component.indexOf("[");
if(openBracketIndex != -1) {
String key = component.substring(0, openBracketIndex);
if(jumper instanceof JSONObject) {
JSONObject jsonObj = (JSONObject)jumper;
jumper = jsonObj.opt(key);
if(jumper == null) {
break;
}
}
if(!(jumper instanceof JSONArray)) {
jumper = null;
break;
}
boolean validValue = false;
int closeBracketIndex = component.indexOf("]", openBracketIndex);
if(closeBracketIndex != -1) {
String bracketString = component.substring(openBracketIndex + 1, closeBracketIndex);
int bracketVal;
try {
bracketVal = Integer.valueOf(bracketString);
JSONArray arr = (JSONArray)jumper;
if(bracketVal < arr.length() && bracketVal >= 0) {
validValue = true;
jumper = arr.opt(bracketVal);
}
} catch(NumberFormatException e) {
//Do nothing
Logger.error("drillJSONObject exception thrown: " + e);
}
}
if(!validValue) {
jumper = null;
}
} else {
JSONObject jsonObj = (JSONObject)jumper;
jumper = jsonObj.opt(component);
}
if(jumper == null) {
break;
}
}
return jumper;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment