Tuesday, May 26, 2015

How to use read JSON objects/Values into selenium through Java

Step 1
1. Open Json file in JSON parser to identify the object array hierarchy
2. Associate java-json.jar file to the eclipse libraries
3. Paste the json content into the parser to figure out the hierarchy to access http://json.parser.online.fr/
4. The sample tweets are identified through text attribute
5. Go through the following code
Sample Code

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;



public class Test {
private static WebDriver driver = null;
public static void main(String[] args) throws IOException, InterruptedException{

driver = new FirefoxDriver();

driver.get("http://webapptoshowtweets/hilton");
Thread.sleep(10000);
Thread.sleep(5000);

try {

URL url = new URL("http://dallas/tweets.json");

URLConnection urlConnection = url.openConnection();

InputStream in = new BufferedInputStream(urlConnection.getInputStream());

BufferedReader r = new BufferedReader(new InputStreamReader(in));

StringBuilder total = new StringBuilder();

String line;

while ((line = r.readLine()) != null) {

total.append(line);

}

in.close();


JSONArray jsonArray = new JSONArray(total.toString());

String[] values=new String[jsonArray.length()];
//System.out.println("Total Tweets: " + jsonArray.length());
for (int index = 0; index < jsonArray.length(); index++) {

JSONObject jsonObject=jsonArray.getJSONObject(index);

String text=jsonObject.getString("text");

String strActTweetDesc = driver.findElement(By.id("tweetsDescription")).getText();

if(strActTweetDesc.equals(text)){
System.out.println("String Matches: Passed" + text);
}
else
{
System.out.println("Tweet Fails");
System.out.println("Expected String: " +text);
System.out.println("Actual Tweet String: " +strActTweetDesc);
}

//Click Next Button
//Selenium get Div Element
//WebElement btnTweetNext = driver.findElement(By.cssSelector("#tweets > #tweetsContainer > #tweetsDescription"));
WebElement btnTweetNext = driver.findElement(By.cssSelector("#tweets > a > div"));
//*[@id="tweets"]/a/div

btnTweetNext.click();
Thread.sleep(1000);

values[index]=text;
//System.out.println(text);


} // for to navigate Json data



} catch (JSONException e) {

e.printStackTrace();

}

}


}

No comments: