Denise Denise - 10 months ago 126
JSON Question

XML to JSON conversion: empty array instead of empty string

I'm using the library net.sf.json to convert an XML to a JSON.
This is the code I wrote:

FileInputStream fis = new FileInputStream("C:\\Desktop\\TestXML.xml");

XMLSerializer xmlSerializer = new XMLSerializer();

JSON json = xmlSerializer.readFromStream(fis);

JSONArray jsonArray = new JSONArray();

JSONObject root = new JSONObject();
root.element("WSJson", jsonArray);

I noticed that if the XML contains empty tags, they are transformed in empty arrays.

Example: given this xml


the output is

"WSJson": [{
"Tipo_Operazione": "I",
"Codice_Prestazione": "SW1",
"Codice_Intervento": [],
"Nome": []

Instead, I would like to have

"WSJson": [{
"Tipo_Operazione": "I",
"Codice_Prestazione": "SW1",
"Codice_Intervento": "",
"Nome": ""

Can anyone help?


why do you need XMLSerialiser to read from file, instead you could use FileReader and XML.toJSONObject() to convert XML string to JsonObject?

public static void main(String[] args) throws FileNotFoundException, IOException {
    String xml = null;
    try(BufferedReader reader = new BufferedReader(new FileReader("C:\\Desktop\\TestXML.xml")))  {
        String readLine =null;
        while((readLine = reader.readLine()) != null)  {
            xml += readLine; 
    JSONObject jsonObject = XML.toJSONObject(xml);