XML to JSON Conversion and Normalization of Unicode Characters
This Groovy script parses XML data from the 'responseBodyTextFromTargetAPI' variable, converts it to JSON format while preserving its hierarchical structure, and translates Unicode escape sequences (including Turkish characters in \uXXXX format) into readable real characters and assigns them to the 'responseBodyTextToClient' variable.
import groovy.json.JsonOutput
import groovy.xml.XmlSlurper
// Clean up "<?...?>" lines
def cleanedXml = responseBodyTextFromTargetAPI.readLines()
.findAll { !it.trim().startsWith("<?") }
.join("\n")
.trim()
// Simplified XML to Map conversion function
def convertToMap(node) {
def map = [:]
// Add attributes starting with @ sign)
node.attributes().each { key, value ->
map["@${key}"] = value.toString()
}
// Check child elements
def hasElements = false
node.children().each { child ->
if (child.name()) {
hasElements = true
def childName = child.name()
// Do child elements have child elements?
def childText = child.text().trim()
def childHasElements = false
child.children().each { grandchild ->
if (grandchild.name()) {
childHasElements = true
}
}
// If there is no child element, use the direct value, if there is, continue recursively
def childValue
if (!childHasElements) {
childValue = childText.isEmpty() ? "" : childText
} else {
childValue = convertToMap(child)
if (childValue.isEmpty()) {
childValue = ""
}
}
// If there is more than one element with the same name, merge them into a list
if (map.containsKey(childName)) {
if (!(map[childName] instanceof List)) {
map[childName] = [map[childName]]
}
map[childName] << childValue
} else {
map[childName] = childValue
}
}
}
return map
}
try {
// XML parse
def xml = new XmlSlurper().parseText(cleanedXml)
def resultMap = [(xml.name()): convertToMap(xml)]
// JSON output - Convert Unicode escape sequences to readable characters
def jsonOutput = new JsonOutput()
def jsonString = jsonOutput.toJson(resultMap)
def prettyJson = jsonOutput.prettyPrint(jsonString)
// Fix Turkish characters
def normalizedJson = prettyJson.replaceAll('\\\\u([0-9A-Fa-f]{4})', { fullMatch, hexValue ->
try {
return new String(Character.toChars(Integer.parseInt(hexValue, 16)))
} catch (Exception e) {
return fullMatch
}
})
responseBodyTextToClient = normalizedJson
} catch (Exception e) {
responseBodyTextToClient = JsonOutput.prettyPrint(JsonOutput.toJson([
error: "XML parsing error: ${e.message}"
]))
}
GROOVY
Response received as XML:
<?xml version="1.0" encoding="UTF-8"?>
<Tarih_Date Tarih="02.05.2025" Date="05/02/2025" Bulten_No="test">
<Currency CrossOrder="0" Kod="1" CurrencyCode="2">
<Unit>
1
</Unit>
<Isim>
2
</Isim>
<CurrencyName>
3
</CurrencyName>
</Currency>
</Tarih_Date>
GROOVY
Transformed JSON Response:
{
"Tarih_Date": {
"@Tarih": "02.05.2025",
"@Date": "05/02/2025",
"@Bulten_No": "test",
"Currency": [
{
"@CurrencyCode": "2",
"@Kod": "1",
"@CrossOrder": "0",
"Unit": "1",
"Isim": "2",
"CurrencyName": "3",
}
]
}
}
GROOVY