XML to JSON Dönüşümü ve Unicode Karakterlerin Normalleştirilmesi
Bu Groovy script, 'responseBodyTextFromTargetAPI' değişkeninden gelen XML veriyi ayrıştırır, hiyerarşik yapısını koruyarak JSON formatına dönüştürür ve Unicode kaçış dizilerini (\uXXXX formatındaki Türkçe karakterler dahil) okunabilir gerçek karakterlere çevirerek 'responseBodyTextToClient' değişkenine atar."
import groovy.json.JsonOutput
import groovy.xml.XmlSlurper
// "<?...?>" satırlarını temizleme
def cleanedXml = responseBodyTextFromTargetAPI.readLines()
.findAll { !it.trim().startsWith("<?") }
.join("\n")
.trim()
// Sadeleştirilmiş XML to Map dönüşüm fonksiyonu
def convertToMap(node) {
def map = [:]
// Attribute'ları ekle (@ işareti ile başlayarak)
node.attributes().each { key, value ->
map["@${key}"] = value.toString()
}
// Alt elementleri kontrol et
def hasElements = false
node.children().each { child ->
if (child.name()) {
hasElements = true
def childName = child.name()
// Çocuk elemanların alt elementleri var mı?
def childText = child.text().trim()
def childHasElements = false
child.children().each { grandchild ->
if (grandchild.name()) {
childHasElements = true
}
}
// Alt element yoksa direkt değeri kullan, varsa recursive devam et
def childValue
if (!childHasElements) {
// Alt element yoksa, metin içeriği boş olsa bile boş string döndür
childValue = childText.isEmpty() ? "" : childText
} else {
// Alt element varsa, recursive map oluştur
childValue = convertToMap(child)
// Eğer bu child tamamen boş ise (hiç değer içermiyorsa) boş string döndür
if (childValue.isEmpty()) {
childValue = ""
}
}
// Aynı isimde birden fazla eleman varsa liste olarak birleştir
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 çıktısı - Unicode kaçış dizilerini okunabilir karakterlere dönüştür
def jsonOutput = new JsonOutput()
def jsonString = jsonOutput.toJson(resultMap)
// Pretty print yap
def prettyJson = jsonOutput.prettyPrint(jsonString)
// Türkçe karakterleri düzelt
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 // Dönüştürülemezse orijinal değeri koru
}
})
responseBodyTextToClient = normalizedJson
} catch (Exception e) {
responseBodyTextToClient = JsonOutput.prettyPrint(JsonOutput.toJson([
error: "XML ayrıştırma hatası: ${e.message}"
]))
}
GROOVY
XML olarak gelen Response:
<?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
Dönüştürülmüş 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