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



我的代码中有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>
'''

如何将此xml转换为json与jsonSlurperClassic?我知道你需要使用toJsonObject方法,然后从它调用toString()并获得json字符串并将其传递给jsonSlurperClassic。我在Groovy Web Console

中尝试了这个
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);

但我得到一个错误:无法解析类JSONObject我做错了什么?链接:https://groovyconsole.appspot.com/script/5119690196123648

您的代码正在使用外部依赖项。当你在自己的机器上运行脚本时,你可以使用Grape@Grab这个依赖项(但是要注意web控制台通常不允许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)

最新更新