2

I have a list of records:

{
  "StatusCode": 200,
  "Result": [
    {
      "Id": 15015600,
      "Amount": 97.41,
      "CreatedDate": "10/17/2018",
    },
    {
      "Id": 15015602,
      "Amount": 682.11,
      "CreatedDate": "10/17/2018",
    },
   and so on...

I'm trying to craft a statement to return the "Id" value when I know the Amount and CreatedDate.

int Id = given()
            .when()
                .get(/EndPoint))
            .then()
                .body("Result.findAll { it.Amount==97.41 }.CreatedDate", hasItems("10/17/2018"));

Is this even possible?

Anton
  • 761
  • 17
  • 40
  • Not really sure what you're trying to achieve here: are you try to consume JSON or to validate it ? – sensei Oct 22 '18 at 15:33

3 Answers3

1

If you have list of records as a List, not as a json String, you can just call

def id = YourResponse.Result.find{it.Amount==97.41 && it.CreatedDate=="10/17/2018"}

It will return you first found result that matches your search condition. If you call findAll instead of find with the same closure, you will have list of all matches.

yeugeniuss
  • 180
  • 1
  • 7
1

The solution:

int i = response.path("Result.find{it.Amount.toDouble()==293.51 && it.CreatedDate=='10/26/2018'}.Id");

I needed to add, "toDouble()" to my query. it.Amount.toDouble()==293.51, not it.Amount==293.51. Once the toDouble() was added the query worked as expected.

Anton
  • 761
  • 17
  • 40
0

It's a bit hard to tell if you have already parsed your JSON, so I included code to do that too. This is plain Groovy, not Rest Assured specific.

import groovy.json.JsonSlurper

def text = '''
{
  "StatusCode": 200,
  "Result": [
    {
      "Id": 15015600,
      "Amount": 97.41,
      "CreatedDate": "10/17/2018",
    },
    {
      "Id": 15015602,
      "Amount": 682.11,
      "CreatedDate": "10/17/2018",
    }
   ]
}'''
def json = new JsonSlurper().parseText(text)
assert json.Result.find{ it.Amount == 97.41 && it.CreatedDate == '10/17/2018' }.Id == 15015600
Paul King
  • 627
  • 4
  • 6
  • I'm really new to groovy and api's in general. How can I use this to pull the Id value out and store it in a variable? You say, "def json = new JsonSlurper()..." and so on but what would that actually look like in some java code? – Anton Oct 22 '18 at 15:20