0

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");
}
Robin Topper
  • 2,295
  • 1
  • 17
  • 25
Aditya
  • 457
  • 2
  • 8
  • 27
  • 1
    "didn't worked' in what way? Also please format your code. – Oleg Aug 07 '17 at 09:03
  • No It didn't worked. – Aditya Aug 07 '17 at 10:07
  • Possible duplicate of [What’s the best way to load a JSONObject from a json text file?](https://stackoverflow.com/questions/7463414/what-s-the-best-way-to-load-a-jsonobject-from-a-json-text-file) – Atty Aug 10 '17 at 13:19

2 Answers2

0

Refer here.

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

Atty
  • 691
  • 13
  • 20
  • If you think the question you link to is similar to this one and has already been answered, you should flag it as a duplicate and not use it as an answer. – Robin Topper Aug 07 '17 at 09:50
  • I don't have the privileges to flag it duplicate. Thats why there is a reference to the original answer. – Atty Aug 07 '17 at 09:53
0

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

r3dst0rm
  • 1,876
  • 15
  • 21