Home > Net >  Is it possible to take element from the API response on Java?
Is it possible to take element from the API response on Java?

Time:11-23

I'm newbie in Java and wanna ask you question. Let's imagine the situation. I generate account for testing purposes using API and in response I get line e.g. such as:

{
 "accountId": "42515896"
}

How could I write method that will take this "42515896" from the response and insert it into some int variable that I declared before?

public class failedAuthorization {
    // created reference variable for WebDriver
    WebDriver driver;

    @BeforeMethod
    public void setup() {

        System.setProperty("webdriver.chrome.driver","C:\\Users\\imagineName.imagineSurname\\chromedriver\\chromedriver.exe");
// initializing driver variable using Chrome Driver
        driver=new ChromeDriver();
        driver.manage().deleteAllCookies();
// launching google.com on the browser
        driver.get("https://login.live.com/");
// maximized the browser window
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);

    }

e.g. I have some API request that generate me account and in response I get data that I will need further to login. How to use generated data?

CodePudding user response:

You probably want to use some external library to parse response to Java object, for example Jackson

Simple solution (using JsonNode):

String jsonString = "{'accountId': '42515896'}";
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(jsonString);
actualObj.get("accountId").textValue(); //returns 42515896

CodePudding user response:

You can use json path:

    public static void main(String[] args) {
        String myJson = "{\"accountId\": \"42515896\"}";
        String accountId = JsonPath.read(myJson, "$.accountId");
        System.out.println(accountId);
    }

Dependency:

<!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.7.0</version>
</dependency>

  • Related