Groovy MarkupBuilder通过引用传递字符串

时间:2014-06-06 19:30:11

标签: groovy markupbuilder

将JSON提要转换为可以由Endeca实例使用的格式,并且由于使用了JsonSlurper和MarkupBuilder等工具,因此决定在Groovy中编写此转换。我们的JSON feed输入看起来像这样(保存为stage / newObject.json):

[
  {
    "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中的数组),即创建&的关闭#34; PVAL" node通过引用传递subField变量,并且它不被视为字符串而是字符数组,因此尝试输出时,我们得到一个Memory位置,而不是String。到目前为止我们已经解决了这个问题,但我想知道是否有更优雅的解决方案:

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())
        }
    }
}

1 个答案:

答案 0 :(得分:2)

将<{1}}更改为

中的subField in field.value.value
subField in field.value

虽然这个逻辑可以简化为

for (subField in field.value) {
    if (subField != null) {
        PROP(NAME: field.key) {
            PVAL(subField)
        }
    }
}