多层嵌套json递归解析工具类
时间: 2023-09-23 07:07:29 浏览: 128
下面是一个简单的工具类,可以递归解析多层嵌套的 JSON 数据:
```java
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonParser {
public static void parse(JSONObject json) {
for (String key : json.keySet()) {
Object value = json.get(key);
if (value instanceof JSONObject) {
System.out.println("Object: " + key);
parse((JSONObject) value);
} else if (value instanceof JSONArray) {
System.out.println("Array: " + key);
parseArray((JSONArray) value);
} else {
System.out.println(key + ": " + value.toString());
}
}
}
private static void parseArray(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if (value instanceof JSONObject) {
System.out.println("Object: " + i);
parse((JSONObject) value);
} else if (value instanceof JSONArray) {
System.out.println("Array: " + i);
parseArray((JSONArray) value);
} else {
System.out.println(i + ": " + value.toString());
}
}
}
}
```
使用示例:
```java
public class TestJsonParser {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"John\",\"age\":30,\"cars\":[{\"name\":\"Ford\",\"models\":[\"Fiesta\",\"Focus\",\"Mustang\"]},{\"name\":\"BMW\",\"models\":[\"320\",\"X3\",\"X5\"]}],\"address\":{\"street\":\"Downing Street 10\",\"city\":\"London\"}}";
JSONObject json = new JSONObject(jsonStr);
JsonParser.parse(json);
}
}
```
输出结果:
```
name: John
age: 30
Array: cars
Object: 0
name: Ford
Array: models
0: Fiesta
1: Focus
2: Mustang
Object: 1
name: BMW
Array: models
0: 320
1: X3
2: X5
Object: address
street: Downing Street 10
city: London
```
阅读全文