How to handle JSON conversion from Karate feature file to Java class?

129 views Asked by At

I have a karate test and lines like this :

* def schema = read('schema.json')
* def response = read('response.json')
And def jsonValidator = Java.type('feature.JsonValidator').isValid(parseSchema, response)

But when I send that schema which is json file instead of

{
  "properties": {
    "debtor": {
      "example": 1,
      "type": "integer"
    },
    "creditor": {
      "example": 2,
      "type": "integer"
    },
    "currency": {
      "example": 3,
      "type": "integer"
    }
  },
  "type": "object"
}

In Java code I am getting it like

{properties={debtor={example=1, type=integer}, creditor={example=2, type=integer}, currency={example=3, type=integer}}, type=object} 

I read that Karate for some reason converts JSON file to Map or List in Java. But how then to have proper JSON in Java class?

1

There are 1 answers

0
Peter Thomas On

If you have a Java class that is a valid Java Bean you can use karate.toBean() to convert from JSON to a Java instance.

You can look at this example:

* def catType = 'com.intuit.karate.demo.domain.Cat'
* def Cat = Java.type(catType)
* def toCat = function(x){ return karate.toBean(x, catType) }
# second argument (true) is to strip keys with null values
* def toJson = function(x){ return karate.toJson(x, true) }

The JSON is expected to be the same "shape" as the Java bean.