Skip to main content

Using JSONobject and JSONarray for parsing json

Did you ever wonder why sometimes you have json with curly brackets while sometimes with square brackets? This is because you were dealing with JSON object and arrays respectively. JSON array organizes collection of related items which can be json object in themselves -


[{"name":"item 1"},{"name": "item2} ]


JSON object usually contains key/value pair of related item. For ex -


{"name": "firstname", "dateOfBirth":"65475645"}


We used Jackson parser in API video tutorial but if you don’t need entire data set from json response of API call then you can parse the API response using JSONArray or JSONObject APIs.
you would use JSONArray to parse JSON which starts with the array brackets.  On the other hand, you would use JSONObject when dealing with JSON that begins with curly braces.


Of course, JSON arrays and objects may be nested inside one another. One common example of this is an API which returns a JSON object containing some metadata alongside an array of the items matching your query:
{"startIndex": 0, "data": [{"name":"item 1"},{"name": "item2"} ]}


We will use the json file available at - https://httpbin.org/get?show_env=1 in following example.
In case httpbin goes down in future, the same json looks as -


{
  • args:
  • {
    • show_env: "1"
  • },
  • headers:
  • {
    • Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    • Accept-Encoding: "gzip, deflate, sdch, br",
    • Accept-Language: "en-US,en;q=0.8,de;q=0.6",
    • Host: "httpbin.org",
    • Runscope-Service: "httpbin",
    • Upgrade-Insecure-Requests: "1",
    • User-Agent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36",
    • X-Forwarded-For: "94.135.236.134",
    • X-Forwarded-Protocol: "https",
    • X-Forwarded-Ssl: "on",
    • X-Real-Ip: "94.135.236.134"
  • },
  • origin: "94.135.236.134",
}


We will use jersey client to get the json response -


// get JSON response
Client client = Client.create();
WebResource webResource = client.resource("https://httpbin.org/get?show_env=1");
ClientResponse clientResponse =  webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
System.out.println(clientResponse.getStatus());
String jsonResponse = clientResponse.getEntity(String.class);
System.out.println(jsonResponse);


Since the output is json object here, we will use JSONObject to parse the response from previous example and print the data we need.
// parse JSON objects
JSONObject jsonObject = new JSONObject(jsonResponse);
System.out.println("headers are: "+jsonObject.getString("headers"));
System.out.println("origin is: "+jsonObject.getString("origin"));
System.out.println("url is: "+jsonObject.getString("url"));


I am just printing the required data points but you can use it carry assert operation to verify if data returned is valid or not.


Now let’s see an example of parsing json array. For this we would use the API call. In case the api goes down in future, this is how the response looks like -


{
  • Content-Length: "137",
  • Content-Type:
  • [
    • "application/json",
    • "text/plain; charset=UTF-8"
  • ],
  • Server: "httpbin"
}


it is a JSON object which contains “Content-Type:” array and we will print all of its values.


// get JSON response
webResource = client.resource("https://httpbin.org/response-headers?Content-Type=text%2Fplain%3B+charset%3DUTF-8&Server=httpbin");
clientResponse =  webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
System.out.println(clientResponse.getStatus());
jsonResponse = clientResponse.getEntity(String.class);
System.out.println(jsonResponse);


// parse JSON Array
jsonObject = new JSONObject(jsonResponse);
JSONArray jsonArray = jsonObject.getJSONArray("Content-Type");
System.out.println("Content-Type json array is: "+jsonArray);


for(int index=0; index<jsonArray.length(); index++) {
  System.out.println("Content at JSON array index: "+index+", "+ jsonArray.get(index));
}

And now you can assert the JSON array data for required values.
Project Download

Popular posts from this blog

Where is my defect ID?

Don't you feel ecstatic when your automated tests find bug? After all tests finding bugs give us a sense of accomplishment, is not it? And this is followed by usual cycle of defect reporting, retesting and hopefully closure of defect. But at times defects are deferred to next or future releases. Which causes test method to fail for subsequent releases. And if you are dealing with a test suite having 100s of tests then it may become difficult to remember if there was a defect reported for a failing test? How do you deal with such situation. How about adding defect-id to @description tag of TestNG test. Hence it is reported on automated test report and we would know if defect exists for a failing test - How do you track defect-id of a failing test?

Return only first or last element from webelements collection

We often come across situation when there are multiple elements on a page and we probably like to exercise only a few of them using selenium webdriver. May be just first and last element. For example on a search result page we may like to click on only first and last link and not all. This is when Iterables API comes handy. (By the way I am assuming that you have already completed watching selenium training videos :)). Once we have collection of web element then we can use Iterables to get only first or last element as following - Consider that we fetch collection of element as - List< WebElement > webElements = getDriver().findElements(By. id ( "htmlID" ));   Now we can get the first web element from this collection as -  WebElement firstElement = Iterables. getFirst (webElements,  getDriver().findElement(By. id ( "defaultElement" )));   Herein second argument -   (getDriver().findElement(By. id ( "defaultElement" )))    in the me

Selenium Tutorial: Pattern Mathing using Selenium

I must confess I have never been admirer of Regular Expression but then there are times you can not escape from it, especially while working on a website which has dynamic contents appeared in static text and you want to validate it. like - "Validate that this text appears and there is 123 here and 456 here" And the test condition is 123 and 456 could be any three digits but number if digits should not be more than three. In a crude way we can at least test this - Assert.assertTrue(selenium.getText("elementLocator").contains("Validate that this text appears and there is")); but what if text goes wrong after "and there is"... what if more than 3 digits appear in text. This is where pattern matching/regular expression comes for our rescue and we can use matches method of String class to achieve same. So the assertion would be - String text = selenium.getText("elementLocator"); Assert.assertTrue(text.matches("Validate