Json 从 XML 转换为单个/多个 children

Json conversion from XML with single / multiple children

我正在使用 org.json 库将 XML 转换为 JSON:

JSONObject json = XML.toJSONObject(xmlData);

我得到 XML 作为 API 响应。 XML (xmlData) 如下所示:

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

当上面的XML转换为JSON时,children 'Student'解析为List。这符合预期。

但是,有时候我的XML只能有一个child。示例:

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

在这种情况下,由于它只有一个 child,因此它被转换为 object 'Student' 而不是 List。因此,在这种情况下,我的 JSON 解析(使用 gson)期望它是 List,但失败了。

我需要有关如何处理此案的建议。我希望 children 被解析为列表,即使它是单个 child!

如果可以更好地处理此问题,我愿意使用任何其他库将 XML 转换为 JSON。

你得到XML后的目的是什么?

来自该项目的 GitHub 页面(以及您的具体方法): Click here to read

Sequences of similar elements are represented as JSONArrays

也许您可以自己创建 JSONObject。这是一个例子:

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);
}