// json_xml.groovy — parse and build JSON and XML. import groovy.json.JsonOutput import groovy.json.JsonSlurper import groovy.xml.MarkupBuilder import groovy.xml.XmlSlurper // ---- JSON: parse def text = '''{"orderId": "PO-4471", "customer": {"name": "Acme"}, "lines": [{"sku": "AX-200", "qty": 24, "price": 8.50}, {"sku": "BX-310", "qty": 2, "price": 40}]}''' def order = new JsonSlurper().parseText(text) println order.customer.name // Acme println order.lines*.sku // [AX-200, BX-310] println order.lines.sum { it.qty * it.price } // 284.00 // ---- JSON: build def payload = [ externalId: order.orderId, entity : [name: order.customer.name], items : order.lines.collect { [item: it.sku, quantity: it.qty, rate: it.price] } ] println JsonOutput.prettyPrint(JsonOutput.toJson(payload)) // ---- XML: parse def xml = ''' Acme ''' def root = new XmlSlurper().parseText(xml) println root.@id // PO-4471 (attribute) println root.Customer.text() // Acme println root.Line.collect { "${it.@sku} x ${it.@qty}" } // [AX-200 x 24, BX-310 x 2] println root.Line.findAll { it.@qty.toInteger() > 5 }.size() // 1 // ---- XML: build def out = new StringWriter() new MarkupBuilder(out).Invoice(number: 'INV-7731') { Customer(order.customer.name) order.lines.each { l -> Item(sku: l.sku, qty: l.qty) } } println out