Make assertions in JSON Response PageObject Selenium Java

I have a following question: In my project I’m using Page Object pattern. When I click some button I recieve a JSON response like that:

{“description”:“Just a sample description for this application [Application Information 0]”, “category”:{“id”:“57a9e39d48f26f74e054b764”,“title”:“Information”},“iconData”:null,“imageData”:null,“author”:{“name”:“admin”,“password”:“21232f297a57a5a743894a0e4a801fc3”,“roleModel”:{“name”:“DEVELOPER”,“id”:“57a9e39d48f26f74e054b762”,“developer”:true,“title”:“DEVELOPER”},“lname”:“Petrov”,“fname”:“Ivan”},“numberOfDownloads”:9,“uploadedTimeStamp”:1470751645983,“title”:“Application Information 0”}

I described a page in project that contains an element “textInJson”

import com.google.gson.JsonElement;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class JsonResponsePage extends BasicPage {
@FindBy(xpath = JSON_RESPONSE_ELEMENT)
JsonElement textInJson;

public static final String JSON_RESPONSE_ELEMENT = "html/body/div[2]/div[3]/div/div[1]/a";

}

And I need to make sure that each parameter has corresponding value (e.g. first you find ‘“numberOfDownloads”:’ and then you make sure that following is ‘9’ and so on.)

How would I implement this in JAVA? I know that I should be using gson library, but don’t really undertand how it works right now, so some examples would be nice.

Thank you very much!

PS: Еще не до конца разобрался как правильно писать слекторы, не обращайте внимания на xpath, просто скопировал из firebug

не знаю насчет gson, но jackson прекрасно справляется с десериализацией

Gson вам в помощь.
Создаете класс, в нем описываете поля, которые в json приходят, и потом выполняете что-то типа
new GsonBuilder().create().fromJson(ваш json, ваш класс) - как-то так. На выходе получаете объект вашего класса и работаете с ним как всегда

Try something like this:

Response resp = get(APIurl);
resp.then().
body(“category”[0].id", equalTo(“57a9e39d48f26f74e054b764”)).
body(“category”[0].title", equalTo(“Information”));

It is approximate. Use your json structure to build correct assertion.

You need rest assured for this, am I right?

Оказалось, что все тривиально:
Использовал библиотеку org.json
С предыдущей страницы получал информацию, которая отображена на странице и засовывал в с список

public ArrayList getAppInfo() {
ArrayList info = new ArrayList();
info.add(getTitle());
info.add(getDescription());
info.add(getCategory());
info.add(getAuthor());
info.add(getNumberOfDownloads());
return info;
}

Затем инфу из json response тоже засовывал в список следующим образом

import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import java.util.ArrayList;

public Object GetInfoFromJsonResponse() throws JSONException {
String jsonText = jsonElement.getText();
ArrayList jsonInfo = new ArrayList();
JSONObject json = new JSONObject(jsonText);
JSONObject category = json.getJSONObject(“category”);
JSONObject author = json.getJSONObject(“author”);
jsonInfo.add((String) json.get(“title”));
jsonInfo.add("Description: " + json.get(“description”));
jsonInfo.add("Category: " + category.get(“title”));
jsonInfo.add(“Author: " + author.get(“name”));
int nOfDownloads = (Integer) json.get(“numberOfDownloads”);
nOfDownloads -= 1;
jsonInfo.add(”# of downloads: " + String.valueOf(nOfDownloads));
return jsonInfo;
}

После этого в тесте делал проверку, что списки совпадают

assertThat(jsonResponsePage.GetInfoFromJsonResponse()).isEqualTo(info);