How to convert xml file to json file using groovy?

Hi,
i`m trying to convert xml file to json file
i tried this:

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

File xml = new File (“C:/temp/test.xml”);
JSONObject json = XML.toJSONObject(xml); // converts xml to json
String jsonPrettyPrintString = json.toString(4); // json pretty print
System.out.println(jsonPrettyPrintString);

it returns:
groovy.lang.MissingMethodException: No signature of method: static org.json.XML.toJSONObject() is applicable for argument types: (java.io.File) values: [C:\temp\test.xml]
Possible solutions: toJSONObject(java.lang.String)

you are getting error because XML.toJSONObject(xml) accepts String not file type.

can you try this?
String xml = ‘copy-your-complete-xml-string-here’;
JSONObject json = XML.toJSONObject(xml);
String jsonPrettyPrintString = json.toString(4);
System.out.println(jsonPrettyPrintString);

Yes it works, thank you.
My file is a bit large and change at each test.
so i did this

StringBuilder sb = new StringBuilder();
BufferedReader br = Files.newBufferedReader(Paths.get(“C:/temp/test.xml”))
// read line by line
String line;
while ((line = br.readLine()) != null)
sb.append(line).append(“\n”)
System.out.println(sb)

String xml = (sb);
JSONObject json = XML.toJSONObject(xml);
String jsonPrettyPrintString = json.toString(4);
System.out.println(jsonPrettyPrintString);

but now i need to save the jsonPrettyPrintString into a json file.

String path = “C:/temp/test.json”;
Files.write( Paths.get(path), jsonPrettyPrintString.getBytes());

it works fine for me.

groovy way is:

    File file = new File(filePath)
    String fileContent = file.text

but your approach is ok too.

1 Like

You can do it all with basic Groovy:

// Given an XML string
def xml = ‘’’
| Tim
| Tom
|’’’.stripMargin()

// Parse it
def parsed = new XmlParser().parseText( xml )

// Convert it to a Map containing a List of Maps
def jsonObject = [ root: parsed.node.collect {
[ node: it.text() ]
} ]

// And dump it as Json
def json = new groovy.json.JsonBuilder( jsonObject )

// Check it’s what we expected
assert json.toString() == ‘{“root”:[{“node”:“Tim”},{“node”:“Tom”}]}’
HOWEVER, you really need to think about certain things…

How are you going to represent Attributes?
Will your XML contain textwootext style markup? If so, how are you going to handle that?
CDATA? Comments? etc?
It’s not a smooth 1:1 mapping between the two… But for a given specific format of XML, it may be possible to come up with a given specific format of Json.

Update:
To get the names from the document (see comment), you can do:

def jsonObject = [ (parsed.name()): parsed.collect {
[ (it.name()): it.text() ]
} ]
Update 2
You can add support for greater depth with:

// Given an XML string
def xml = ‘’’
| Tim
| Tom
|
| another
|
|’’’.stripMargin()

// Parse it
def parsed = new XmlParser().parseText( xml )

// Deal with each node:
def handle
handle = { node ->
if( node instanceof String ) {
node
}
else {
[ (node.name()): node.collect( handle ) ]
}
}
// Convert it to a Map containing a List of Maps
def jsonObject = [ (parsed.name()): parsed.collect { node ->
[ (node.name()): node.collect( handle ) ]
} ]

// And dump it as Json
def json = new groovy.json.JsonBuilder( jsonObject )

// Check it’s what we expected
assert json.toString() == ‘{“root”:[{“node”:[“Tim”]},{“node”:[“Tom”]},{“node”:[{“anotherNode”:[“another”]}]}]}’
Again, all the previous warnings still hold true (but should be heard a little louder at this point) :wink:

Hi,
For me the cmd: ‘BufferedReader br = Files.newBufferedReader(Paths.get(“C:/temp/test.xml”))’
does not work, I have this error message

2021-04-22 23:04:45.351 DEBUG testcase.xml compare 2 - 4: br = Files.newBufferedReader(Paths.get(“C:/ReferenceFile/Ref-Form.xml”))
2021-04-22 23:04:45.433 ERROR c.k.katalon.core.main.TestCaseExecutor - :x: Test Cases/3 compare 2 XML/xml compare 2 FAILED.
Reason:
groovy.lang.MissingPropertyException: No such property: Files for class: Script1619123213870
at xml compare 2.run(xml compare 2:38)
at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)

Is there another way to convert the xml file into a string ?
Thanks