Created
April 13, 2017 11:36
-
-
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.
This file contains hidden or 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
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Assuming that any key doesn't contain dot "."