代码之家  ›  专栏  ›  技术社区  ›  user846316

具有单个/多个子项的XML Json转换

  •  0
  • user846316  · 技术社区  · 7 年前

    我正在使用org。用于将XML转换为json的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>
    

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

    我需要一个关于如何处理这个案子的建议。我希望孩子们被解析为列表,即使是独生子女!

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   Roni Koren Kurtberg    7 年前

    获取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);
    }
    
    推荐文章