我需要将Json文件格式转换为XML格式,我已经看到很多网页甚至在java中使用它我可以看到有很多人能够做到但我找不到在groovy上的方式。
我有一个像这样的文件:
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
我希望能够直接转换为XML,因为我们需要使用它来动态创建操作请求。
先谢谢你们
答案 0 :(得分:2)
她是可以帮助你的link。
基于上面的链接,这里是完整的groovy脚本。
import net.sf.json.JSON
import net.sf.json.JSONSerializer
import net.sf.json.xml.XMLSerializer
String str = '''{ "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } } }'''
JSON json = JSONSerializer.toJSON( str )
XMLSerializer xmlSerializer = new XMLSerializer()
xmlSerializer.setTypeHintsCompatibility( false )
String xml = xmlSerializer.write( json )
System.out.println(xml)
顺便说一句,您需要下载library并将其添加到类路径,在这种情况下,请将其复制到SOAPUI_HOME / bin / ext目录下。
答案 1 :(得分:0)
有underscore-java库,其中包含来自Json和toXml的静态方法。
@Grab('com.github.javadev:underscore:1.32')
import com.github.underscore.lodash.$
def json = '''
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
'''
println $.toXml($.fromJson(json))
输出:
<?xml version="1.0" encoding="UTF-8"?>
<glossary>
<title>example glossary</title>
<GlossDiv>
<title>S</title>
<GlossList>
<GlossEntry>
<ID>SGML</ID>
<SortAs>SGML</SortAs>
<GlossTerm>Standard Generalized Markup Language</GlossTerm>
<Acronym>SGML</Acronym>
<Abbrev>ISO 8879:1986</Abbrev>
<GlossDef>
<para>A meta-markup language, used to create markup languages such as DocBook.</para>
<GlossSeeAlso>
<element>GML</element>
<element>XML</element>
</GlossSeeAlso>
</GlossDef>
<GlossSee>markup</GlossSee>
</GlossEntry>
</GlossList>
</GlossDiv>
</glossary>