Java 如何以一个json数据返回所有的部门机器子级本门信息
时间: 2024-05-02 08:21:57 浏览: 2
假设有如下部门机器信息的JSON数据:
```json
{
"dept1": {
"machines": [
{
"id": "1",
"name": "machine1"
},
{
"id": "2",
"name": "machine2"
}
]
},
"dept2": {
"machines": [
{
"id": "3",
"name": "machine3"
},
{
"id": "4",
"name": "machine4"
}
],
"subDept": {
"dept3": {
"machines": [
{
"id": "5",
"name": "machine5"
},
{
"id": "6",
"name": "machine6"
}
]
}
}
}
}
```
我们可以使用递归的方式遍历所有部门及其子部门,然后取出部门中的机器信息。
以下是一个Java代码示例:
```java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonStr = "{\"dept1\":{\"machines\":[{\"id\":\"1\",\"name\":\"machine1\"},{\"id\":\"2\",\"name\":\"machine2\"}]},\"dept2\":{\"machines\":[{\"id\":\"3\",\"name\":\"machine3\"},{\"id\":\"4\",\"name\":\"machine4\"}],\"subDept\":{\"dept3\":{\"machines\":[{\"id\":\"5\",\"name\":\"machine5\"},{\"id\":\"6\",\"name\":\"machine6\"}]}}}}";
JSONObject jsonObj = JSON.parseObject(jsonStr);
JSONObject result = new JSONObject();
getSubDeptMachines(jsonObj, "dept2", result);
System.out.println(result.toJSONString());
}
private static void getSubDeptMachines(JSONObject jsonObj, String deptName, JSONObject result) {
JSONObject deptObj = jsonObj.getJSONObject(deptName);
if (deptObj != null) {
// 取出部门中的机器信息
result.put(deptName, deptObj.get("machines"));
// 递归处理子部门
JSONObject subDeptObj = deptObj.getJSONObject("subDept");
if (subDeptObj != null) {
for (String subDeptName : subDeptObj.keySet()) {
getSubDeptMachines(subDeptObj, subDeptName, result);
}
}
}
}
}
```
运行结果为:
```json
{
"dept2": [
{
"id": "3",
"name": "machine3"
},
{
"id": "4",
"name": "machine4"
},
{
"id": "5",
"name": "machine5"
},
{
"id": "6",
"name": "machine6"
}
],
"dept3": [
{
"id": "5",
"name": "machine5"
},
{
"id": "6",
"name": "machine6"
}
]
}
```