java读取json文件,并且用递归获取json内 类型为string的字段名,并保留json的层级结构,将字段名保存到一个能循环的参数中
时间: 2025-06-15 09:20:15 浏览: 11
在Java中,我们可以使用`org.json`库来处理JSON数据,特别是通过递归来遍历并获取字符串类型的字段名。下面是一个简单的示例,展示了如何读取JSON文件并使用递归获取所有字符串字段:
```java
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonReader {
public static void main(String[] args) {
// JSON文件路径替换为你实际的文件路径
String jsonString = readJsonFile("path_to_your_json_file.json");
JSONObject jsonObject = new JSONObject(jsonString);
getStrings(jsonObject, new ArrayList<String>());
}
private static String readJsonFile(String filePath) {
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
StringBuilder jsonBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
jsonBuilder.append(line).append('\n');
}
return jsonBuilder.toString();
} catch (IOException e) {
throw new RuntimeException("Error reading JSON file", e);
}
}
private static void getStrings(JSONObject obj, List<String> fieldNames) {
if (obj == null) return;
Iterator<String> keys = obj.keys();
while (keys.hasNext()) {
String key = keys.next();
Object value = obj.get(key);
if (value instanceof JSONObject || value instanceof JSONArray) {
getStrings((JSONObject) value, fieldNames);
} else if (value instanceof String) {
fieldNames.add(key);
}
}
}
}
```
在这个例子中,我们首先读取JSON文件内容,然后创建一个`JSONObject`。`getStrings()`函数递归地遍历每个键值对,如果遇到的是嵌套的对象或数组,继续递归;如果是字符串,则添加到`fieldNames`列表中。
运行此程序后,`fieldNames`列表会包含JSON文件中所有字符串类型的字段名,它们按照层级结构排列。
阅读全文
相关推荐

















