如何在 Groovy 中使用 jsonSlurperClassic 将 XML 转换为 json?

How to convert XML to json with jsonSlurperClassic in Groovy?

我有 XML 我的代码

def xml = 
'''
<path>
    <testdata>
        <item>
            <resourceURI>https://localhost/version/</resourceURI>
            <relativePath>/test/folder/version/</relativePath>
            <text>version</text>
            <leaf>false</leaf>
            <lastModifiedtest>2021-07-03</lastModifiedtest>
            <sizeOnDisk>-1</sizeOnDisk>
        </item>
    </testdata>
</path>
'''

如何使用 jsonSlurperClassic 将此 xml 转换为 json? 我知道您需要使用 toJsonObject 方法,然后从中调用 toString() 并获取 json 字符串并将其传递给 jsonSlurperClassic。 我用 Groovy Web 控制台

试过了
import groovy.json.JsonSlurperClassic
def xml = 
'''
<path>
    <testdata>
        <item>
            <resourceURI>https://localhost/version/</resourceURI>
            <relativePath>/test/folder/version/</relativePath>
            <text>version</text>
            <leaf>false</leaf>
            <lastModifiedtest>2021-07-03</lastModifiedtest>
            <sizeOnDisk>-1</sizeOnDisk>
        </item>
    </testdata>
</path>
'''
JSONObject json = XML.toJSONObject(xml);
String jsonPrettyPrintString = json.toString(4);
System.out.println(jsonPrettyPrintString);

但我得到一个错误:无法解析 class JSONObject 我究竟做错了什么? Link: https://groovyconsole.appspot.com/script/5119690196123648

您的代码正在使用外部依赖项。当你在自己的机器上 运行 一个脚本时,你可以使用 Grape@Grab 依赖关系(但要注意网络控制台通常不允许 Grape 下载文件)。

@Grab(group='org.json', module='json', version='20210307')
import org.json.XML

String xml = '''\
<path>
    <testdata>
        <item>
            <resourceURI>https://localhost/version/</resourceURI>
            <relativePath>/test/folder/version/</relativePath>
            <text>version</text>
            <leaf>false</leaf>
            <lastModifiedtest>2021-07-03</lastModifiedtest>
            <sizeOnDisk>-1</sizeOnDisk>
        </item>
    </testdata>
</path>''';

println XML.toJSONObject(xml).toString(4)

输出将是

{"path": {"testdata": {"item": {
    "relativePath": "/test/folder/version/",
    "resourceURI": "https://localhost/version/",
    "text": "version",
    "leaf": false,
    "sizeOnDisk": -1,
    "lastModifiedtest": "2021-07-03"
}}}}

JsonSlurperJsonSlurperClassic 不用于读取 JSON,而不用于读取 XML 或写入 JSON)