3. The code accesses the nested “store” object using jsonObject.get(“store”) and casts it to a JsonObject. It then retrieves specific fields from this “store” object.
JsonObject store = (JsonObject) jsonObject.get("store");
4. Extracts the “book” field and casts it to a String, then prints it.
String book = (String) store.get("book");
System.out.println("Book: " + book);
5. Extracts the “author” field and casts it to a String, then prints it.
3. The code assumes that within the “store” object, there is a key “book” which corresponds to a JSON array. It retrieves this array and stores it in a JsonArray variable named books.
// Accessing the "store" object
JsonObject store = (JsonObject) jsonObject.get("store");
// Accessing the "book" array
JsonArray books = (JsonArray) store.get("book");
4. A for-each loop iterates over each element in the books array. Each element is considered an object, and it’s cast to JsonObject named book. Within each iteration, several attributes of the book JSON object are accessed like category, author, title, price
5. The code accesses the nested “bicycle” object using jsonObject.get(“bicycle”) and casts it to a JsonObject. It then retrieves specific fields from this “bicycle” object. Extracts the “color” and “price” field and casts it to a String and BigDecimal, then prints it.
// Accessing the "bicycle" object
JsonObject bicycle = (JsonObject) store.get("bicycle");
String color = (String) bicycle.get("color");
BigDecimal bicyclePrice = (BigDecimal) bicycle.get("price");
System.out.println("Bicycle: Color - " + color + ", Price - " + bicyclePrice);
6. Extracts the “expensive” field and casts it to a BigDecimal, then prints it.
In this tutorial, I will explain to pass a JSON or XML file as a payload to the request. This is needed when the payload is static or there is minimal change in the request payload. This can be done by using the body() method, which accepts “File” as an argument. This is elaborated in Javadoc.
RequestSpecification body(File body)
This specifies file content that’ll be sent with the request. This only works for the POST, PATCH and PUT HTTP methods. Trying to do this for the other HTTP methods will cause an exception to be thrown.
Add Rest Assured dependency to the project. Use the latest version from here.
There are two modes, strict and non-strict in JSONAssert. In most cases, you will probably want to set strict to false, since that will make the tests less brittle. Strict tests require all the elements requested to be returned, and only those elements (ie, the tests are non-extensible). Arrays of elements must be returned to the same order as expected.
In Lenient mode, extensibility will be allowed, and no strict ordering will be checked. Let’s see example programs for comparing JSON Arrays.
Comparing two Exact same JSON Arrays – LENIENT Mode
import org.json.JSONArray;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
public class JsonArrayAssertDemo {
@Test
public void sameArray() {
// same no of elements, values and in same order
String jsonArray1 = "[\"Vibha\",\"Abha\",\"Nysha\"]";
String jsonArray2 = "[\"Vibha\",\"Abha\",\"Nysha\"]";
JSONAssert.assertEquals(jsonArray1, jsonArray2, JSONCompareMode.LENIENT);
}
}
The output of the above program is
Comparing two JSON Arrays with the same fields but different in order – Lenient
@Test
public void sameArrayDifferentOrder() {
// Same no of elements but different order
String jsonArray1 = "[\"Vibha\",\"Abha\",\"Nysha\"]";
String jsonArray2 = "[\"Nysha\",\"Vibha\",\"Abha\"]";
JSONAssert.assertEquals(jsonArray1, jsonArray2, JSONCompareMode.LENIENT);
}
The output of the above program is
LENIENT mode does not care about the order of the fields in the JSON.
Comparing two JSON Arrays with the same fields but different in order – Strict
@Test
public void sameArrayDifferentOrder_Strict() {
// same no of elements, values and in same order
String jsonArray1 = "[\"Vibha\",\"Abha\",\"Nysha\"]";
String jsonArray2 = "[\"Nysha\",\"Vibha\",\"Abha\"]";
JSONAssert.assertEquals(jsonArray1, jsonArray2, JSONCompareMode.STRICT);
}
The output of the above program is
STRICT mode cares about the order of the fields in the JSON Array.
Comparing two JSON Arrays with the same fields but different values
@Test
public void sameArrayDifferentValue() {
// Same no of elements but different values
String jsonArray1 = "[\"Vibha Singh\",\"Abha\",\"Nysha\"]";
String jsonArray2 = "[\"Vibha\",\"Abha\",\"Nysha\"]";
JSONAssert.assertEquals(jsonArray1, jsonArray2, JSONCompareMode.LENIENT);
}
The output of the above program is
In this scenario assertEquals() will fail as a value is not matching.
Comparing two JSON Arrays with the case sensitivity
@Test
public void sameArrayCaseSensitive() {
// case sensitive
String jsonArray1 = "[\"VIbha\",\"Abha\",\"Nysha\"]";
String jsonArray2 = "[\"Vibha\",\"Abha\",\"Nysha\"]";
JSONAssert.assertEquals(jsonArray1, jsonArray2, JSONCompareMode.LENIENT);
}
The output of the above program is
Comparing two JSON Arrays with the same fields but different datatype of values
Here, both the JSON Arrays have the same structure, but we have added one more attribute to the second one. In this case, the assertion fails as it counts the number of items in the arrays.
Comparing two JSON Arrays with the addition – STRICT mode
The compare mode can also be defined by using an overloaded method that takes boolean instead of JSONCompareMode where LENIENT = false and STRICT = true.
There are two modes, strict and non-strict in JSONAssert. In most cases, you will probably want to set strict to false, since that will make the tests less brittle. Strict tests require all the elements requested to be returned, and only those elements (ie, the tests are non-extensible). Arrays of elements must be returned to the same order as expected.
In Lenient mode extensibility will be allowed and no strict ordering will be checked. Let’s see example programs for comparing JSONs.
Comparing two Exact same JSON Objects – LENIENT Mode
Here, both the JSONs have the same structure, but we have added one more attribute to the second one. In this case, the assertion matches the first string with the second one and it looks the same. So, the test passes.
Let us reverse the assertion now. We are comparing the jsonObject2 which has 3 attributes with jsonObject1 which has 2 attributes. So, salary is not present in jsonObject1. In this case, the test fails.
The compare mode can also be defined by using an overloaded method that takes boolean instead of JSONCompareMode where LENIENT = false and STRICT = true.
To validate a JSON schema in Java, you can use libraries that provide support for JSON schema validation. JsonSchemaValidator is a Hamcrest matcher that can be used to validate that a JSON document matches a given JSON schema.
Add the following dependency in pom.xml. You can check the latest Maven dependency from here.
We canpretty-print a JSON using thetoString(int indentFactor) method of org.json.JSONObject class, where indentFactor is the number of spaces to add to each level of indentation.
public java.lang.String toString(int indentFactor)
Let us create a JSON Object.
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
public class Json_Demo {
@Test
public void passBodyAsJsonArray1() {
// Creating JSON array to add first JSON object
JSONArray array1 = new JSONArray();
array1.put(new JSONObject().put("firstname", "Tom").put("lastname", "Mathew").put("age", 59).put("salary",
720000));
// Creating JSON array
JSONArray array2 = new JSONArray();
array2.put(new JSONObject().put("firstname", "Perry").put("lastname", "David").put("age", 32).put("salary",
365000));
// Create JSON Object to add JSONArrays
JSONObject data1 = new JSONObject();
data1.put("employee1", array1);
data1.put("employee2", array2);
System.out.println(data1);
}
}
The output of the above program is
Add toString(int indentFactor) method to the above program.
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
public class Json_Demo {
@Test
public void passBodyAsJsonArray1() {
// Creating JSON array to add first JSON object
JSONArray array1 = new JSONArray();
array1.put(new JSONObject().put("firstname", "Tom").put("lastname", "Mathew").put("age", 59).put("salary",
720000));
// Creating JSON array
JSONArray array2 = new JSONArray();
array2.put(new JSONObject().put("firstname", "Perry").put("lastname", "David").put("age", 32).put("salary",
365000));
// Create JSON Object to add JSONArrays
JSONObject data1 = new JSONObject();
data1.put("employee1", array1);
data1.put("employee2", array2);
System.out.println(data1.toString(4));
}
}
The output of the above program is
Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!