I need to convert Json file format into XML format, I've seen a lot of webpages that use this even in java I can see there are a lot of people who are capable of doing it but I can't find a way on groovy.
I have a file like this one:
{
"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"
}
}
}
}
}
And I'd like to be able to convert directly to XML, since we need to use that to dynamically create the request for an operation.
Thank you in advance guys
Her is the link that can help you.
Based on the above link, here is the complete groovy script for the same.
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)
By the way, you need to download the library and add it to the classpath, in this case copy it under SOAPUI_HOME/bin/ext directory.
There is underscore-java library with static methods fromJson and 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))
output:
<?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>