当然,你可以使用 JSONPath 来做也可以,那样比较强大,简单的方法如下:
-
- * Return JSON object value via JSON path, like data/list/demo
- *
- * @param jsonObject JSON object to parse
- * @param path JSON path, support array as well, for example: "/abc/xyz[1]/bbb/ccc"
- * @return if exists return the json object, otherwise return null
- */
- public static Object getDataByPath(JSONObject jsonObject, String path) {
- String[] keys = path.split("/");
- Object obj = null;
- JSONObject currentObject = jsonObject;
- for (int i = 0; i < keys.length; i++) {
-
- String key = keys[i];
- int index = -1;
- int startIndex = key.indexOf("[");
- int endIndex = key.indexOf("]");
- if (startIndex > 0 && endIndex > startIndex) {
- index = Integer.parseInt(key, startIndex + 1, endIndex, 10);
- if (index >= 0) {
- key = key.substring(0, startIndex);
- }
- }
- if (currentObject.containsKey(key)) {
- obj = currentObject.get(key);
- if (obj instanceof JSONArray && index >= 0) {
- JSONArray array = (JSONArray) obj;
- if (index < array.size()) {
- obj = array.get(index);
- }
- }
- if (obj instanceof JSONObject) {
- currentObject = (JSONObject) obj;
- } else {
- return i == keys.length - 1 ? obj : null;
- }
- } else {
- return null;
- }
- }
- return obj;
- }