Skip to content

Instantly share code, notes, and snippets.

@piyush-malaviya
Created April 13, 2017 11:36
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 piyush-malaviya/4ac6381d39dcfa9bbd073e1bd18a93be to your computer and use it in GitHub Desktop.
Save piyush-malaviya/4ac6381d39dcfa9bbd073e1bd18a93be to your computer and use it in GitHub Desktop.
JsonUtils, JSON parsing made easy. Simply pass the json object and the path to the key you want, and it will return value if available, otherwise it will return null. Works well with simple JSONObject and Gson's JsonObject.
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
import java.util.Map;
public class JsonUtils {
/**
* get value for key
*
* @param jsonObject jsonObject
* @param key key for value. for inner object key must be followed by parent and period "."
* for ex: {"name": {"firstName": { ... } } } name.firstName
* @return JsonElement (JsonObject or JsonArray)
*/
public static JsonElement getJsonObjectForKey(JsonObject jsonObject, String key) {
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
String keyName = entry.getKey();
if (key.contains(keyName)) {
if (key.contains(".")) {
String newKey = key.substring(key.indexOf(".") + 1);
if (entry.getValue() instanceof JsonObject) {
return getJsonObjectForKey((JsonObject) entry.getValue(), newKey);
}
} else {
return entry.getValue();
}
}
}
return null;
}
public static Object getJsonObjectForKey(JSONObject jsonObject, String key) {
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
// get key
String keyName = (String) iterator.next();
// get value of that key
try {
Object object = jsonObject.get(keyName);
if (key.contains(keyName)) {
if (key.contains(".")) {
String newKey = key.substring(key.indexOf(".") + 1);
if (object instanceof JSONObject) {
return getJsonObjectForKey((JSONObject) object, newKey);
}
} else {
return object;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
@piyush-malaviya
Copy link
Author

Assuming that any key doesn't contain dot "."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment