0

I'm trying to fetch all the element names and values from a JSON. Basically, I will be getting a JSON response and need to compare it to an XML response. The approach I have decided on for now is to get all element names and values from both the JSON and the XML, and then store them in separate lists. Finally, I will just compare the lists.

Q1. Is there a better way to do what I am planning? (Compare JSON to XML)

If no, I'm facing some troubles while doing this. My JSON is a nested JSON and I need to fetch the values of ALL elements and their names. However, using the JSON, I am able to get only the outermost element. I need this fetch to be dynamic since I want to re-use the same code later for other similar comparisons

(Using a sample XML I found in another answer on StackOverflow)

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import groovy.json.JsonBuilder;
import java. util.ArrayList;
import java. util.Iterator
import groovy.json.JsonSlurper

xml = """
{
"master": {
   "node": "xyz", 
   "files": [{"type": "modified", "file": "test.txt"}]
   }, 
"testbranch2": {
   "node": "abc", 
   "files": [{"type": "modified", "file": "test.txt"}] 
   }, 
"testbranch": {
   "node": "xxx", 
   "files": [{"type": "modified", "file": "test.txt"}], 
   }
}
"""

def json = new JSONObject(xml);
def test = new JsonSlurper().parseText(json.toString())
log.info test.keySet() 
log.info test.Outer.keySet()

The json.keys() only manages to get the outermost key, and not all.

Thanks in advance!

Vinay Prajapati
  • 7,199
  • 9
  • 45
  • 86

1 Answers1

0

You could use jackson to convert xml to json / JsonNode and then easily compare to any level you want.

See link below to see how to convert xml to json. How to convert XML to JSON using only Jackson?

Vinay Prajapati
  • 7,199
  • 9
  • 45
  • 86