Denise Denise - 5 months ago 88
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();
jsonArray.add(json);

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

<WSJson>
<Tipo_Operazione>I</Tipo_Operazione>
<Codice_Prestazione>SW1</Codice_Prestazione>
<Codice_Intervento></Codice_Intervento>
<Nome/>
</WSJson>


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?

Answer

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);
    System.out.println(jsonObject.toString(1));
}