0

I'm trying to get Json response by selenium webdriver. How to get it as a Json format. Currently what I get is a String format.

Here is what I'm trying to get: {"id":377,"text":"Playing Sudoku is fun!"}

<pre style="word-wrap: break-word; white-space: pre-wrap;">{"id":377,"text":"Playing Sudoku is fun!"}</pre>

Here is my code:

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class GameTestSelenuim {

public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver","/Users/lulu/Desktop/Selenium/chromedriver");
    WebDriver driver = new ChromeDriver();
    driver.get("http://localhost:8080/game");
    driver.manage().window().maximize();
    String text = driver.findElement(By.cssSelector("pre")).getText();
    System.out.println(text);
}

}

1 Answer 1

2

Selenium getText() method always returns a string value. You can convert the json string value to JSON object using any JSON library.

Here I used org.json library.

public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver","/Users/lulu/Desktop/Selenium/chromedriver");
    WebDriver driver = new ChromeDriver();
    driver.get("http://localhost:8080/game");
    driver.manage().window().maximize();
    String text = driver.findElement(By.cssSelector("pre")).getText();
    System.out.println(text);
    JSONObject jsonobject = new JSONObject(text);
    System.out.println(jsonobject.getString("text"));
    System.out.println(jsonobject.getInt("id"));
}

JSONObject jsonobject = new JSONObject(text) - Here we create JSON object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.