首页 > 解决方案 > 将 xml 转换为 json 不会以相同的形式打印 xml

问题描述

我正在尝试将 xml 转换为 json,我想使用 1:1

<dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180813</version>
        </dependency>

但问题是转换后的输出形式不一样。代码:

JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
            String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
            System.out.println(jsonPrettyPrintString);

xml:

<?xml version="1.0" encoding="UTF-8"?>
<!--Anagrafica del clienti del mercato-->
<anagrafica>
    <testata>
        <nomemercato id="007">Mercato di test</nomemercato>
        <data>Giovedi 18 dicembre 2003 16.05.29</data>
    </testata>
    <record>
        <codice_cliente>5</codice_cliente>
        <rag_soc>Miami American Cafe</rag_soc>
        <codice_fiscale>IT07654930130</codice_fiscale>
        <indirizzo tipo="casa">Viale Carlo Espinasse 5, Como</indirizzo>
        <num_prodotti>13</num_prodotti>
    </record>
    ...
</anagrafica>

我得到了代码

{"anagrafica": {
    "record": [
        {
            "codice_fiscale": "IT07654930130",
            "rag_soc": "Miami American Cafe",
            "num_prodotti": 13,
            "codice_cliente": 5,
            "indirizzo": {
                "tipo": "casa",
                "content": "Viale Carlo Espinasse 5, Como"
            }
        ....
    ],
    "testata": {
        "data": "Giovedi 18 dicembre 2003 16.05.29",
        "nomemercato": {
            "id": "007",
            "content": "Mercato di test"
        }
    }
}}

正如你所看到testata的,record 我的意思是 testata 应该是第一个,然后是记录。你能告诉我如何解决这个问题吗?或者我应该用什么来使它正确?

标签: javajsonxml

解决方案


推荐阅读