【发布时间】:2020-12-31 11:23:08
【问题描述】:
我从 JSON 文件中获取了一个嵌套的 JSON 数组(“投资”),但当我尝试使用它时,该数组似乎为空。
我的 JSON 文件:
{
"invested": [
{
"email" : "test@test.com",
"password" : "test"
}
],
"notInvested": [
{
"email" : "test@test.com",
"password" : "test"
}
]}
这是我从文件中获取 JSONObject 的方法:
public JSONObject returnJSONObject(String path) throws JSONException, IOException
{
path = System.getProperty("user.dir") + path;
JSONObject obj = parseJSONFile(path);
return obj;
}
public static JSONObject parseJSONFile(String filename) throws JSONException, IOException
{
String content = new String(Files.readAllBytes(Paths.get(filename)));
Reporter.log(content);
return new JSONObject(content);
}
这就是失败的地方。当我尝试调用'loginPage.login(loginArray.get(0).toString(), loginArray.get(1).toString());';
JSONObject validLogins = returnJSONObject("valid-user-logins.json");
JSONArray loginArray = (JSONArray) validLogins.get("invested");
// submit valid credentials
loginPage.login(loginArray.get(0).toString(), loginArray.get(1).toString());
我在运行程序时返回的错误是我的索引 0 超出了长度 0 的范围:
org.json.JSONException: JSONArray initial value should be a string or collection or array.
我对 JSON 很陌生,所以这仍然有点令人困惑,关于我做错了什么有什么想法吗?任何帮助将不胜感激!
编辑: 为了澄清起见,我试图从 json 文件中的“投资”数组中获取“电子邮件”和“密码”。
【问题讨论】: