Peter Peter - 2 months ago 25
Groovy Question

Groovy converting json to xml with anonymous array fails

I have following code to convert json to xml:

import grails.converters.JSON
import grails.transaction.Transactional
import org.json.JSONObject
import org.json.XML

@Transactional
class JsonService {

def convertJsonToXml(String json) {
JSONObject o = JSON.parse(json)
return XML.toString(o)
}

}


This code works fine, except of jsons with anonymous arrays.
For example:

[
{
"cnt":1,
"name":"American",
"pk":7
},
{
"cnt":2,
"name":"Celebrities",
"pk":3
},
{
"cnt":1,
"name":"Female",
"pk":2
}
]


I get this result:
{"empty":false}

How can I avoid this problem?

Answer

you are mixing up libraries: right now you are parsing the json string via grails.converters.JSON, which will produce org.codehaus.groovy.grails.web.json.JSONElement objects.

then you are trying to fit this result into an org.json.JSONObject to let it convert to XML via org.json.XML

just parse the String via org.json.JSONTokener, and make the variable "o" dynamic (to hold JSONObject or JSONArray):

import org.json.JSONObject
import org.json.JSONTokener
import org.json.XML

def convertJsonToXml(String json) {
    def o = new JSONTokener(json).nextValue()
    return XML.toString(o)
}