Pages

Read data from JSON file ?

How to Read data from JSON file ?

Regarding Object Repository in frameworks, we are using Properties file, Excel Files and text files.
Here we can see how to JSON file as object repository. For example, i have json file say "./objectrepo.json." in framework and is has web page elements like below:
{
  "Window"            : "linkText;Introduction to collections",
  "AnotherWindow" : "linkText;Overview on Collections"
}

How to get elements from JSON file:
public class JsonReadData {
public static void main(String[] args) throws IOException, ParseException {
WebDriver driver;
System.setProperty("webdriver.chrome.driver", ".\\library\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://keeplearners.blogspot.in/");
driver.manage().window().maximize();
JSONParser parser = new JSONParser();
//creating an object for json file
Object obj = parser.parse(new FileReader(".\\CucumberProject\\src\\test\\elements\\home_page.json"));
//converting Object obj to JSONObject
JSONObject jsonObject = (JSONObject) obj;
// Prints all data in json file
System.out.print(jsonObject);
//Get the required key value in string type
String getvalue= (String) jsonObject.get("Window");
//Using split method, get locator type and locator value in array
String[] values=getvalue.split(";");
System.out.println("locatorType="+values[0] + "\n" +"locatorValue="+ values[1]);
//return locator type like ID,Name,class etc.,.
String locatorType=values[0];
//return locator type value
String locatorValue=values[1];
if(locatorType.equalsIgnoreCase("linkText")){
driver.findElement(By.linkText(locatorValue)).click();
System.out.println("clicked");
}
}
Output:
JSON file data={"Window":"linkText;Introduction to collections","AnotherWindow":"linkText;Overview on Collections"}
locatorType=linkText
locatorValue=Introduction to collections
clicked
So in our existing frameworks also we can directly use json file as above.
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.