2

I have the below JSON structure and I am trying to retrieve the name order/sale/Cancel to a string variable in groovy

{"Transaction" : {"Order" : { ......
{"Transaction" : {"Sale" : { ......
{"Transaction" : {"Cancel" : { ......

I was able to get to this point, reading the JSON using JSON slurper with some research but not sure how to get read the name.. most of the articles I have seen the point to reading the values and not the name.

final BufferedReader inReader = new BufferedReader(new InputStreamReader(inputStream, 'UTF-8'))
Object result = jsonSlurper.parse(inReader)

I have converted from XML to JSON so if this can be done using either XML or JSON would help.

Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76
anuj
  • 21
  • 1

2 Answers2

2

Correct would be to use :

def json = '{"Transaction" : {"Order" : "result"} }'

def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(json)

assert 'Order' == result.Transaction.keySet().first()
injecteer
  • 20,038
  • 4
  • 45
  • 89
0

If you have JSON in String you don't need to create BufferedReader, just use parseText. After you parse JSON you can just access it by traversing properties.

def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(inputStream.text)​;

result.Transaction.Order​ //result
Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76