javar实现json树形结构
时间: 2024-05-14 19:18:46 浏览: 72
可以使用 JSON-Lib 库来实现 JSON 树形结构,以下是一个示例代码:
```java
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonTree {
public static void main(String[] args) {
String jsonString = "{\n" +
" \"name\": \"root\",\n" +
" \"children\": [\n" +
" {\n" +
" \"name\": \"child1\",\n" +
" \"children\": [\n" +
" {\n" +
" \"name\": \"grandchild1\",\n" +
" \"children\": []\n" +
" },\n" +
" {\n" +
" \"name\": \"grandchild2\",\n" +
" \"children\": []\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"name\": \"child2\",\n" +
" \"children\": []\n" +
" }\n" +
" ]\n" +
"}";
JSONObject jsonObject = JSONObject.fromObject(jsonString);
printJsonObject(jsonObject);
}
private static void printJsonObject(JSONObject jsonObject) {
String name = jsonObject.getString("name");
System.out.println(name);
JSONArray children = jsonObject.getJSONArray("children");
for (int i = 0; i < children.size(); i++) {
JSONObject childObject = children.getJSONObject(i);
printJsonObject(childObject);
}
}
}
```
以上代码将 JSON 字符串解析为 JSONObject 对象,然后通过递归的方式遍历 JSON 树形结构并打印节点名称。你可以根据需要修改代码来适应你的需求。
阅读全文