1
將JSON提要轉換爲可由我們的Endeca實例使用的格式,並由於諸如JsonSlurper和MarkupBuilder等工具而在Groovy中編寫此轉換。我們的JSON飼料投入看起來像這樣(保存爲舞臺/ newObject.json):Groovy MarkupBuilder通過引用傳遞字符串
[
{
"Name": "Object Name",
"DimID": 0000,
"ObjectID": "Object-0000",
"TypeID": 1,
"Type": "Object Type",
"Description": "A Description",
"DirectorID": "007",
"DirectorName": "Bond, James",
"ParentObjectID": null,
"ObjectLevelID": 1,
"ObjectLevel": "MI-6",
"ProjectNumbers": [
"0001",
"0002"
],
"ManagerIDs": [
"001"
],
"ManagerNames": [
"M"
],
"SubObjectIDs": [
"006",
"005"
],
"TaskNumbers": [
"001"
],
"ProjectNames": [
"Casino Royal",
"Goldfinger",
"License to Kill"
]
}
]
而且我必須做轉換的代碼是這樣的:
def rawJSONFile = new File("stage/newObject.json")
JsonSlurper slurper = new JsonSlurper()
def slurpedJSON = slurper.parseText(rawJSONFile.text)
def xmlOutput = new MarkupBuilder(new FileWriter(new File("stage/ProcessedOutput.xml")))
xmlOutput.RECORDS() {
for (object in slurpedJSON) {
RECORD() {
for (field in object) {
if (field.value != null) {
if (field.value.value.class.equals(java.util.ArrayList)) {
if (field.value.value.size > 0) {
for (subField in field.value.value) {
if (subField != null) {
PROP(NAME: field.key) {
PVAL(subField)
}
}
}
}
} else {
PROP(NAME: field.key) {
PVAL(field.value)
}
}
}
}
}
}
}
我們的問題體驗大約是groovy腳本的一半,它處理子字段(即JSON中的數組),創建「PVAL」節點的閉包通過引用傳遞subField變量,並且它不被視爲字符串但一個字符數組,所以試圖做輸出,我們得到一個內存位置,而不是一個字符串。到目前爲止,我們已經有了解決辦法是這樣的,但我想知道是否有一個更優雅的解決方案:
for (subField in field.value.value) {
if (subField != null) {
PROP(NAME: field.key) {
StringBuilder subFieldValue = new StringBuilder();
for(int i =0; i<subField.length; i++){
subFieldValue.append(subField[i])
}
PVAL(subFieldValue.toString())
}
}
}