I am getting a nested JSON array ("invested") from within a JSON file, but the array appears to be empty when I try to use it.
My JSON file:
{
"invested": [
{
"email" : "test@test.com",
"password" : "test"
}
],
"notInvested": [
{
"email" : "test@test.com",
"password" : "test"
}
]}
Here is how I get the JSONObject from file:
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);
}
And here is where it fails. When I try to call '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());
The error i get back when I run the program says that my index 0 is out of bounds for length 0:
org.json.JSONException: JSONArray initial value should be a string or collection or array.
I am quite new to JSON so this is all still a bit confusing, Any ideas on what I am doing wrong? Any help would be greatly appreciated!
EDIT: For clarification, I am trying to grab the "email" & "password" from the "invested" array in the json file.
The arrays in your sample file only contain one element each.
JSONArray investedArray = (JSONArray) validLogins.get("invested");
JSONArray notInvestedArray = (JSONArray) validLogins.get("notInvested");
JSON reminder:
object: { key : value, key : value, ... }
array: [ value, value, ... ]
Your sample file is:
{ key : array, key : array }
or
{ key : [ object ], key : [ object ] }
You are not pulling the email and password out of the object within the JSON array correctly.
loginArray
contains a JSON array, with one element in it, a JSON object. loginArray.get(0)
has the following value:
{
"email" : "test@test.com",
"password" : "test"
}
You are attempting to convert this entire object to a string, when you want to be pulling out the values of the individual properties within this object.
To obtain the email address, use loginArray.getJSONObject(0).getString("email")
. This gets the first element out of loginArray
as a JSONObject
, and then reads the value of the email
property of this JSONObject
as a string.
To obtain the password, use loginArray.getJSONObject(0).getString("password")
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.