JSON 通用的根據節點路徑獲取節點值的方法

2021-10-01 04:12:21 字數 1295 閱讀 5266

目錄

1. 基本需求

2. 路徑示例

3. **實現

輸入原始資料,路徑,要能夠獲取路徑對應的值

針對jsonarray(陣列),如果路徑包含位置資訊,則查詢對應位置;否則查詢全量陣列,直到找到為止

包含陣列的路徑:#/201908020/data/0/itemlist/0/itemimg     #/201908020/data/0/itemlist/17/itemimg

不包含陣列的路徑:#/201908020/data/itemlist/itemid

注:這種路徑是json schema校驗結果展示所用示例

說明:入參要為jsonobject或者jsonarray

/**

* get json node by path, path example: #/201908020/data/0/itemlist/3/itemimg

** @param data json

* @param path target node path

* @return string of target node value

*/private string getjsonnodebypath(object data, string path)

path = path.startswith("#") ? path.replacefirst("#", "") : path;

path = path.startswith("/") ? path.replacefirst("/", "") : path;

if (!path.contains("/")) else if (data instanceof jsonarray)

} else

}if (data instanceof jsonobject)

if (((jsonobject) data).get(node) instanceof jsonarray) else

} else if (data instanceof jsonarray)

return getjsonnodebypath(jsonarray.get(index), path.substring(pathnodes[0].length() + pathnodes[1].length() + 1));

}for (int index = 0, length = jsonarray.length(); index < length; index++) }}

return null;

}

根據Path取Json指定節點的值

以下方法為根據path取json節點值得方法,廢話不多說,先上 json中陣列的形式如 test 0 其中test為jsonobject值,0為陣列的下標 該方法會對jsonobject和jsonarray進行處理 private jsonobject getobj jsonobject obj,s...

xml獲取指定節點的路徑

引用自http www.w3school.com.cn xpath xpath syntax.asp xpath 使用路徑表示式來選取 xml 文件中的節點或節點集。節點是通過沿著路徑 path 或者步 steps 來選取的。我們將在下面的例子中使用這個 xml 文件。harry potter 29...

xml獲取指定節點的路徑

引用自 xpath 使用路徑表示式來選取 xml 文件中的節點或節點集。節點是通過沿著路徑 path 或者步 steps 來選取的。我們將在下面的例子中使用這個 xml 文件。harry potter 29.99 learning xml 39.95 xpath 使用路徑表示式在 xml 文件中選取...