Utilize the JsonPath
feature from RestAssured
as it is an excellent library for parsing JSON Objects and Arrays.
Include this Maven Dependency:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>3.3.0</version>
</dependency>
To parse JSON, provide the data as a String
or File
, then use JsonPath.from()
method and pass the data as an argument.
Sample JSON Structure:
{
"data": {
"ACCOUNT": [
{
"AmountDue": "$36,812.99",
"OutstandingBalance": "$27,142.27",
"StatementTotal": "$9,670.72",
"StatementDate": "12/6/2018",
"DueByDate": "12/23/2018",
"AccountNumber": "5-029-5685-55"
},
{
"AmountDue": "$40,000.00",
"OutstandingBalance": "$27,142.27",
"StatementTotal": "$9,670.72",
"StatementDate": "12/6/2018",
"DueByDate": "12/23/2018",
"AccountNumber": "5-029-5685-55"
}
]
}
}
Here's how you can implement it in code:
JsonPath path = JsonPath.from("{\r\n" +
" \"data\": {\r\n" +
" \"ACCOUNT\": [\r\n" +
" {\r\n" +
" \"AmountDue\": \"$36,812.99\",\r\n" +
" \"OutstandingBalance\": \"$27,142.27\",\r\n" +
" \"StatementTotal\": \"$9,670.72\",\r\n" +
" \"StatementDate\": \"12/6/2018\",\r\n" +
" \"DueByDate\": \"12/23/2018\",\r\n" +
" \"AccountNumber\": \"5-029-5685-55\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"AmountDue\": \"$40,000.00\",\r\n" +
" \"OutstandingBalance\": \"$27,142.27\",\r\n" +
" \"StatementTotal\": \"$9,670.72\",\r\n" +
" \"StatementDate\": \"12/6/2018\",\r\n" +
" \"DueByDate\": \"12/23/2018\",\r\n" +
" \"AccountNumber\": \"5-029-5685-55\"\r\n" +
" }\r\n" +
" ]\r\n" +
" }\r\n" +
"}");
System.out.println(path.getString("data.ACCOUNT[1].AmountDue"));
Create a JsonPath
instance using unparsed String data, followed by using path.getString()
to extract the desired value. Adjust the index if you want to retrieve AmountDue
from a different account.
The line
System.out.println(path.getString("data.ACCOUNT[1].AmountDue"));
will output
$40,000.00
If changed to
System.out.println(path.getString("data.ACCOUNT[0].AmountDue"));
, it will print
$36,812.99