Skip to content

Instantly share code, notes, and snippets.

@ferronrsmith
Created August 4, 2013 06:03
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 ferronrsmith/6149364 to your computer and use it in GitHub Desktop.
Save ferronrsmith/6149364 to your computer and use it in GitHub Desktop.
/**
* The following function does a top-down recursive decent on a json tree to
* find an element with-in structure
*
* @param value -value to retrieve
* @param jObj -json object to traverse
* @param deep - deep traversal
* @return JsonElement if found or null if element not found
*/
public JsonElement get(String value, JsonObject jObj, boolean deep) {
// check current level for the key before descending
if (jObj.isJsonObject() && jObj.has(value)) {
// determines if a deep traversal should be done
// if the value is not a primitive (which means it's an object)
// continue traversing. if it is a primitive return that value
if(deep) {
if(jObj.isJsonPrimitive() || jObj.get(value).isJsonPrimitive())
return jObj.get(value);
return get(value, jObj.get(value).getAsJsonObject(), deep);
} else return jObj.get(value);
}
// get all entry sets
Set<Entry<String, JsonElement>> entries = jObj.entrySet();
for (Entry<String, JsonElement> entry : entries) {
// cache the current value since retrieval is done so much
JsonElement curVal = entry.getValue();
if (curVal.isJsonArray()) {
for (JsonElement el : curVal.getAsJsonArray()) {
// recursively traverse the sub-tree
JsonElement res = get(value, el.getAsJsonObject(), deep);
if (res != null)
return res;
}
} else if (curVal.isJsonObject()) {
// traverse sub-node
return get(value, curVal.getAsJsonObject(), deep);
}
}
// when a deep traversal is performed the function will recursively search until a matching key <K,V> is found
// if the value is not a primitive type the iteration continues.
// if searched value is not a primitive and the function reaches the end of the recursion it will return the
// bottom-most search level
// |-k---|
// |--k--| << return this since the last level doesn't have the key
// |-----|
return deep ? jObj : null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment