首页  编辑  

简单的根据 JSON 路径 path 返回对象数据的方法

Tags: /Java/   Date Created:
当然,你可以使用 JSONPath 来做也可以,那样比较强大,简单的方法如下:

  1.   /**
  2.    * Return JSON object value via JSON path, like data/list/demo
  3.    *
  4.    * @param jsonObject JSON object to parse
  5.    * @param path       JSON path, support array as well, for example: "/abc/xyz[1]/bbb/ccc"
  6.    * @return if exists return the json object, otherwise return null
  7.    */
  8.   public static Object getDataByPath(JSONObject jsonObject, String path) {
  9.     String[] keys = path.split("/");
  10.     Object obj = null;
  11.     JSONObject currentObject = jsonObject;
  12.     for (int i = 0; i < keys.length; i++) {
  13.       // Parse array path, xyz[n] ==> key=xyz, index=n
  14.       String key = keys[i];
  15.       int index = -1;
  16.       int startIndex = key.indexOf("[");
  17.       int endIndex = key.indexOf("]");
  18.       if (startIndex > 0 && endIndex > startIndex) {
  19.         index = Integer.parseInt(key, startIndex + 1, endIndex, 10);
  20.         if (index >= 0) {
  21.           key = key.substring(0, startIndex);
  22.         }
  23.       }
  24.       if (currentObject.containsKey(key)) {
  25.         obj = currentObject.get(key);
  26.         if (obj instanceof JSONArray && index >= 0) {
  27.           JSONArray array = (JSONArray) obj;
  28.           if (index < array.size()) {
  29.             obj = array.get(index);
  30.           }
  31.         }
  32.         if (obj instanceof JSONObject) {
  33.           currentObject = (JSONObject) obj;
  34.         } else {
  35.           return i == keys.length - 1 ? obj : null;
  36.         }
  37.       } else {
  38.         return null;
  39.       }
  40.     }
  41.     return obj;
  42.   }