4

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?

Denise
  • 43
  • 1
  • 5

2 Answers2

0

What is wrong in traversing the JSON object in order to replace the empty arrays with empty strings? It is explained here how to do it:

Traverse all the Nodes of a JSON Object Tree with JavaScript

Community
  • 1
  • 1
ceving
  • 21,900
  • 13
  • 104
  • 178
0

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));
}
Vijay
  • 542
  • 4
  • 15