【问题标题】:Json conversion from XML with single / multiple children具有单个/多个子级的 XML 的 Json 转换
【发布时间】:2018-04-14 13:40:29
【问题描述】:

我正在使用 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 时,子 'Student' 被解析为 List。这符合预期。

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

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

在这种情况下,由于它只有一个孩子,因此它被转换为对象“学生”而不是列表。因此,我的 JSON 解析(使用 gson),期望它是 List,在这种情况下失败。

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

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

【问题讨论】:

标签: java json xml gson org.json


【解决方案1】:

你拿到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);
}

【讨论】:

  • 感谢您的回复。我可以这样做,但是我必须知道响应中是否只有一个孩子。所以基本上,我必须在转换之前解析 XML!我正在寻找一种简单的方法来执行此操作,而不是解析和检查孩子的数量!
  • 这就是我在那里添加 try-catch 的原因。如果有多个学生,将引发异常。如果是一名学生,代码将毫无例外地运行。你在这里抓住了这两种情况,不是吗?
猜你喜欢
  • 2021-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-01
  • 2023-01-03
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多