【问题标题】:How to add wrapper while converting JSON array object into XML in Java如何在 Java 中将 JSON 数组对象转换为 XML 时添加包装器
【发布时间】:2017-09-12 10:07:36
【问题描述】:

我想将 JSON 数组转换为 XML,但在转换过程中会生成无效的 XML 文件:

String str = "{ 'test' : [ {'a' : 'A'},{'b' : 'B'}]}"; 
JSONObject json = new JSONObject(str);
String xml = XML.toString(json);

我按照Converting JSON to XML in Java中的建议使用了上面的代码

但如果我尝试将 JSON 对象转换为 XML,它会给出无效的 XML(错误:The markup in the document following the root element must be well-formed.),即

<test><a>A</a></test><test><b>B</b></test>

谁能告诉我如何从 JSON 数组中获取有效的 XML 或如何在转换为 XML 时包装 JSON 数组?

提前致谢。

【问题讨论】:

    标签: java arrays json xml


    【解决方案1】:

    XML 文档只能有一个根元素。您的 XML 结果实际上是:

    <test>
        <a>A</a>
    </test>
    <test>
        <b>B</b>
    </test>
    

    第二个test 元素明显位于文档根元素结束标记之后。 XML.toString 有一个很好的重载接受对象和字符串来封装结果 XML:

    final String json = getPackageResourceString(Q43440480.class, "doc.json");
    final JSONObject jsonObject = new JSONObject(json);
    final String xml = XML.toString(jsonObject, "tests");
    System.out.println(xml);
    

    现在输出的 XML 格式正确:

    <tests>
        <test>
            <a>A</a>
        </test>
        <test>
            <b>B</b>
        </test>
    </tests>
    

    【讨论】:

      猜你喜欢
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 2017-11-30
      • 2018-04-16
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      相关资源
      最近更新 更多