java获取多层JSON的数据,在获取最底层数据的时候,也这个最底层数据的最顶数据是谁
时间: 2023-08-16 22:08:36 浏览: 43
在获取多层 JSON 数据时,你可以通过递归的方式遍历整个 JSON 对象,直到找到最底层的数据。在遍历过程中,你可以记录每个数据的父节点,这样就可以在找到最底层数据时,也同时知道它的最顶层数据是谁。
举个例子,假设你想要获取如下 JSON 数据中 `name` 为 `"Mary"` 的最底层数据的最顶层数据是谁:
```json
{
"id": 1,
"name": "John",
"children": [
{
"id": 2,
"name": "Bob",
"children": [
{
"id": 3,
"name": "Mary"
}
]
},
{
"id": 4,
"name": "Alice",
"children": []
}
]
}
```
你可以使用如下的 Java 代码来实现:
```java
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public static String getTopLevelData(JSONObject json, String targetName) {
String topLevelName = json.getString("name");
JSONArray children = json.getJSONArray("children");
for (int i = 0; i < children.length(); i++) {
JSONObject child = children.getJSONObject(i);
String childName = child.getString("name");
if (childName.equals(targetName)) {
return topLevelName;
} else {
String result = getTopLevelData(child, targetName);
if (result != null) {
return result;
}
}
}
return null;
}
public static void main(String[] args) {
String jsonString = "{\"id\":1,\"name\":\"John\",\"children\":[{\"id\":2,\"name\":\"Bob\",\"children\":[{\"id\":3,\"name\":\"Mary\"}]},{\"id\":4,\"name\":\"Alice\",\"children\":[]}]}";
JSONObject json = new JSONObject(jsonString);
String targetName = "Mary";
String topLevelName = getTopLevelData(json, targetName);
System.out.println("The top level name for " + targetName + " is " + topLevelName);
}
}
```
这个代码的输出结果应该是:
```
The top level name for Mary is Bob
```
这里的 `getTopLevelData` 方法使用了递归的方式遍历 JSON 对象。如果找到了目标数据,就返回它的父节点的 `name` 值;如果当前节点不是目标数据,则递归调用 `getTopLevelData` 方法来查找它的子节点。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)