1
  1. Using java with selenium
  2. I have captured full json in my code
  3. IN my json there are two nodes "Service1" and "Service2"
  4. My requirement is to fetch the details of "Services1" node -->data node
  5. But i am not able to extract only Service1 with data node details(i do not want "test" node details.

Question: Can you please help me to extract data from Service1-with data node only using java code?I am using selenium with java.I need this for one of the script.

 Actual response:
    {
"Service1": [
    {
        "data": {
            "status": false,
            "type": "A",
            "order": 1,
            "Version": "v6"
        },
        "test": {
            "ModuleID": "123456",
            "BoxID": "a777",
            "Url": "https://google.com"

        }

    },
    {
       "data": {
            "status": true,
            "type": "B",
            "order": 1,
            "Version": "v2"
        },
        "test": {
            "ModuleID": "123456",
            "BoxID": "a777",
            "Url": "https://google.com"


        }
    }

],
"Service2": {
   "data1": {
            "status": false,
            "type": "c",
            "order": 1,
            "Version": "v6"
        },
        "dashboard": {
            "ModuleID": "123456",
            "BoxID": "a777",
            "Url": "https://google.com"

        }
}
}

Expected data :
[
  {
    "status": false,
    "type": "A",
    "order": 1,
    "Version": "v6"
   },
  {
   "status": true,
   "type": "B",
   "order": 1,
   "Version": "v2"
  }
  ]
akhouri
  • 69
  • 1
  • 8
  • Do you want to read data from your JSON file and get values of Service1 collection ? – Menai Ala Eddine - Aladdin Mar 24 '18 at 19:23
  • yes, i want values of Service1 collection with data node only .IN Service1 collection there are two nodes one is "data" another is "test".I want Service1 with data node details. – akhouri Mar 24 '18 at 19:25
  • @MenaiAlaEddine I am getting the response in my java code (using eclipse) .I want to read the data from code not from any file. – akhouri Mar 24 '18 at 19:43
  • @MenaiAlaEddine i need one more help i have response like:{ "box": { "data1": false, "data2": false, "v3": false, "data4": "v4" }, "food": { "servicedata": { "name": "abc", "title": "ak", "caption": "abc", "new": { "info": "test" }, "imageUrl": "https://google.com" }, "url": "https://google.com" } } i want food-->Servicedata-->title , i am using the same code but error :org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray is coming – akhouri Mar 26 '18 at 10:19
  • solved using same :) – akhouri Mar 26 '18 at 11:01

2 Answers2

2

Fetching the required data is based on the api response. But in the result of the fetched data you can convert it as you want in java as:

Main theme:

JSONObject response = new JSONObject("json data");//replace json data with your given json data
JSONArray service1 = response.getJSONArray("Service1");
JSONObject firstObjectInService1 = service1.getJSONObject(0);
JSONObject secondObjectInService1 = service1.getJSONObject(1);
JSONObject dataInFirstObject = firstObjectInService1.getJSONObject("data");
JSONObject dataInSecondObject = secondObjectInService1.getJSONObject("data");

Full code snippet:

import org.json.*;
public class JsonParsing {
public static void main(String[] args) {
    String jsonData = "{\n" +
            "\"Service1\": [\n" +
            "    {\n" +
            "        \"data\": {\n" +
            "            \"status\": false,\n" +
            "            \"type\": \"A\",\n" +
            "            \"order\": 1,\n" +
            "            \"Version\": \"v6\"\n" +
            "        },\n" +
            "        \"test\": {\n" +
            "            \"ModuleID\": \"123456\",\n" +
            "            \"BoxID\": \"a777\",\n" +
            "            \"Url\": \"https://google.com\"\n" +
            "\n" +
            "        }\n" +
            "\n" +
            "    },\n" +
            "    {\n" +
            "       \"data\": {\n" +
            "            \"status\": true,\n" +
            "            \"type\": \"B\",\n" +
            "            \"order\": 1,\n" +
            "            \"Version\": \"v2\"\n" +
            "        },\n" +
            "        \"test\": {\n" +
            "            \"ModuleID\": \"123456\",\n" +
            "            \"BoxID\": \"a777\",\n" +
            "            \"Url\": \"https://google.com\"\n" +
            "\n" +
            "\n" +
            "        }\n" +
            "    }\n" +
            "\n" +
            "],\n" +
            "\"Service2\": {\n" +
            "   \"data1\": {\n" +
            "            \"status\": false,\n" +
            "            \"type\": \"c\",\n" +
            "            \"order\": 1,\n" +
            "            \"Version\": \"v6\"\n" +
            "        },\n" +
            "        \"dashboard\": {\n" +
            "            \"ModuleID\": \"123456\",\n" +
            "            \"BoxID\": \"a777\",\n" +
            "            \"Url\": \"https://google.com\"\n" +
            "\n" +
            "        }\n" +
            "}\n" +
            "}";
    System.out.println(jsonData);

    try {
        JSONObject response = new JSONObject(jsonData);//replace json data with your given json data
        JSONArray service1 = response.getJSONArray("Service1");
        JSONObject firstObjectInService1 = service1.getJSONObject(0);
        JSONObject secondObjectInService1 = service1.getJSONObject(1);
        JSONObject dataInFirstObject = firstObjectInService1.getJSONObject("data");
        JSONObject dataInSecondObject = secondObjectInService1.getJSONObject("data");
        System.out.println(dataInFirstObject);
        System.out.println(dataInSecondObject);
    } catch (JSONException je) {
        //do what you want
    }
}
}

so finally in dataInFirstObject we have:

{
   "status": false,
   "type": "A",
   "order": 1,
   "Version": "v6" 
}

and dataInSecondObject we have:

{
    "status": true, 
    "type": "B",
    "order": 1,
    "Version": "v2"
}
Mohan
  • 1,164
  • 15
  • 18
  • hope this will helps you...! – Mohan Mar 24 '18 at 19:53
  • i have integrated above code but getting error:The constructor JSONObject(String) is undefined -->remove argument to match JSONOBject() in the first line. – akhouri Mar 24 '18 at 20:05
  • have you tried to insert json data in the JSONObject() constructor, it worked for me. – Mohan Mar 25 '18 at 19:21
  • In order to use JSONObject , you need to import org.json.*; download the json.jar file and import it into your project then this error will be disappeared. – Mohan Mar 26 '18 at 06:30
  • you can find the json.jar file to download in the following link: http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm – Mohan Mar 26 '18 at 06:31
1

You can use JSON simple library ,it is library used to read/write/parse data in JSON file.In this example i read data from JSON file not a JSON content directly.

 private void findData() {

   ArrayList<String> dataArrayList=new ArrayList<>();

try {

    JSONParser parser = new JSONParser();
    InputStream in = getClass().getResourceAsStream("/json/Services.json");
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    Object obj = parser.parse(reader);
    JSONObject jsonObject = (JSONObject) obj;

    JSONArray msg = (JSONArray) jsonObject.get("Service1");
    Iterator<JSONObject> iterator = msg.iterator();

    while (iterator.hasNext()) {
        JSONObject jsonObjectData = iterator.next();
        JSONObject dataObject = (JSONObject) jsonObjectData.get("data");
        System.out.println(dataObject); 
        //Extract values 
  dataObject.values().stream().forEach(value->{
                    System.out.println(value);
     dataArrayList.add(value.toString());

                });
    }

} catch (IOException | org.json.simple.parser.ParseException ex) {
    Logger.getLogger(CorporationRegistrationFormController.class.getName()).log(Level.SEVERE, null, ex);
}

}  

If you need read JSON content from your code just replace the reader with your content like this : Object obj = parser.parse("JSON content");

  • @MenaiAlaEddineThanks i am able to get the data node.But is it possible to get all data node of Service1 in a single array format like i have mentioned in expected array.Because now i want to extract the values from the filtered data nodes like type, order,url. – akhouri Mar 24 '18 at 20:27
  • You can create an ArrayList and add your values into this array. – Menai Ala Eddine - Aladdin Mar 24 '18 at 20:42
  • I have integrated same code getting o/p as objects are : "{"status":false,"type":"A","order":"1","url":1} objects are : {"status":false,"type":"B","order":"2","url":1} objects are : {"status":false,"type":"A","order":"3","url":1}....what should I make the changes to get all result in single array in the above solution?So that i extract the value like status, order, url for each data node?Can u plz help. – akhouri Mar 24 '18 at 21:06
  • But each data has different values ,do you want a single array contains all values of all data like this : false,A,1,v6,true,B,..... ? – Menai Ala Eddine - Aladdin Mar 24 '18 at 21:16
  • @akhouri i edited my answer according to your needs (all values in same array). – Menai Ala Eddine - Aladdin Mar 24 '18 at 21:28
  • Thank you so much it helped a lot.My issue is resolved :) – akhouri Mar 24 '18 at 21:40