简体   繁体   中英

JSON : how to save JSON Array using Java and loop till last JSON Object

I'm new to JSON and have below file. I have to save the array "steps" in java and need to loop the objects "duration" , "status" and "Keyword".

"steps": [
      {
        "result": {
          "duration": 7128811788,
          "status": "passed"
        },
        "line": 5,
        "name": "The Browser is Launched and Smart Business URL is loaded",
        "match": {
          "location": "Common_Login.the_Browser_is_Launched_and_Smart_Business_URL_is_loaded()"
        },
        "keyword": "Given "
      },]

I tried below but didn't worked.

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("./target/JSON/Output.json"));
JSONArray jsonArray = (JSONArray) obj;
System.out.println(jsonArray);

for (int i = 0; i < jsonArray.size(); i++) {
    JSONObject jsonObjectRow = (JSONObject) jsonArray.get(i);
    name = (String) jsonObjectRow.get("duration");
    id = (String) jsonObjectRow.get("status");
    uri = (String) jsonObjectRow.get("name");
    status = (String) jsonObjectRow.get("location");
}

Refer here .

There are so many libraries build in for doing this task. But look at the question above.

If you want to use the built-in class from Java you can have a look here:

https://stackoverflow.com/a/17399110/3977134

You are missing the part from the parseJson function in the referenced answer.

For simplicity I'd suggest to you to use org.json which is just one of many good libraries to use for JSON parsing in Java. If you are interested see here:

Parse JSON with org.json

Parsing JSON in Java Using org.json

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM