Java将XML转换为JSON并确定是否为数组或对象

时间:2014-02-25 17:18:08

标签: java xml json

我需要将XML转换为JSON,并且我有以下代码可以正常工作。但是,当XML元素实际上应该转换为数组时,就会出现问题。我的问题分为两部分:

1)在xml中表示数组的正确方法是什么?

这是我目前正在使用的xml。元素的内容实际上应该是一个数组。因此,元素[0]应该是其中的元素。

<project id="200">
    <name>test</name>
    <elements>
        <element>
            <id>body</id>
            <width>200</width>
            <height>400</height>
            <children/>
        </element>
    </elements>
</project>

2)如何将xml转换为包含JSON数组和对象的JSON?

private String xmlToJson(String xml) throws IOException {

    JSONObject jsonObject = XML.toJSONObject(xml);

    return jsonObject.toString(4);

} // End of XML to JSON

非常感谢

2 个答案:

答案 0 :(得分:1)

有一个带有静态方法-fno-strict-aliasing的{​​{3}}库。它支持特殊属性array =“ true”,该属性强制元素为数组。我是该项目的维护者。

$machine = Machine::find($id);
    $documents = $machine->documents;

    foreach($documents as $document)
    {

    }



    dd($documents);

    return view('machine.detail', compact('machine'));

输出:

U.xmlToJson(xml)

答案 1 :(得分:0)

回答你的第一个问题:What is the proper way to represent an array in xml?

请参阅:http://www.w3.org/2005/07/xml-schema-patterns.html#Vector

相关问题