import org.json.JSONObject;
import org.json.JSONArray;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadJSONFile {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
// 读取JSON文件
Object obj = parser.parse(new FileReader("path/to/your/file.json"));
// 将对象转换为JSONObject
JSONObject jsonObject = (JSONObject) obj;
// 获取键值对
String name = (String) jsonObject.get("name");
long age = (Long) jsonObject.get("age");
// 打印结果
System.out.println("Name: " + name);
System.out.println("Age: " + age);
// 如果JSON文件中包含数组
JSONArray array = (JSONArray) jsonObject.get("arrayKey");
for (Object item : array) {
System.out.println(item);
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}
org.json.simple
库来解析JSON文件。确保你已经添加了该库到项目中。FileReader
读取JSON文件内容,并使用parser.parse()
方法将其解析为一个对象。JSONObject
类型,以便于后续操作。jsonObject.get("key")
方法获取JSON对象中的键值对。JSONArray
进行遍历和处理。请确保替换"path/to/your/file.json"
为实际的JSON文件路径。
上一篇:java timestamp
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站