Created
October 11, 2015 15:25
-
-
Save natanavra/2f50a65d1f1c7c87de57 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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