Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

java - Nested array in JSONObject is returning as empty (org.json)

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" : "[email protected]",
        "password" : "test"
    }
],
"notInvested": [
    {
        "email" : "[email protected]",
        "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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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" : "[email protected]",
    "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").


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...