Search code examples
javajsonxmlgsonorg.json

Json conversion from XML with single / multiple children


I'm using org.json library to convert XML into JSON:

JSONObject json = XML.toJSONObject(xmlData);

I get the XML as API response. The XML (xmlData) looks like below:

<StudentsTable>
  <Student name = "a" surname = "b" age = "15" />
  <Student name = "x" surname = "y" age = "14" />
</StudentsTable>

When the above XML converted to JSON, the children 'Student' is resolved as List. This is as expected.

However, sometimes my XML can have only one child. Example:

<StudentsTable>
  <Student name = "a" surname = "b" age = "15" />
</StudentsTable>

In this case, since its only one child, it is converted to the object 'Student' instead of the List. Therefore, my JSON parsing (using gson), which expects it to be List, fails in this case.

I need an advice on how to handle this case. I want the children to be resolved as List even if its single child!

I am open to using any other library for XML to JSON conversion if that can handle this better.


Solution

  • What is your purpose after getting the XML?

    From the GitHub page of this project (and your specific method): Click here to read

    Sequences of similar elements are represented as JSONArrays
    

    Maybe you can create by your own the JSONObject. Here is an example:

    public static void main(String[] args) throws IOException {
        String singleStudentXmlData = "<StudentsTable>\n" +
                "  <Student name = \"a\" surname = \"b\" age = \"15\" />\n" +
                "</StudentsTable>";
    
        JSONObject jsonObject = XML.toJSONObject(singleStudentXmlData);
        try {
            JSONObject students = new JSONObject().put("Students", new JSONArray().put(jsonObject.getJSONObject("StudentsTable").getJSONObject("Student")));
            jsonObject.put("StudentsTable", students);
        } catch (JSONException e){
            // You can continue with your program, this is multi student case (works for your by default library behavior)
        }
    
        simpleTest(jsonObject);
    }
    
    private static void simpleTest(JSONObject modifiedJSONObject){
    
        String multiStudentXmlData = "<StudentsTable>\n" +
                "  <Student name = \"a\" surname = \"b\" age = \"15\" />\n" +
                "  <Student name = \"a\" surname = \"b\" age = \"15\" />\n" +
                "</StudentsTable>";
    
        JSONObject multiStudentJSONObject = XML.toJSONObject(multiStudentXmlData);
    
        assert(modifiedJSONObject == multiStudentJSONObject);
    }