为什么这个 Apache Camel 路由没有将 JSON 转换为 XML?

Why Does This Apache Camel Route Not Convert JSON to XML?

我正在尝试使用 Apache Camel 路由将一些 JSON 转换为 XML。下面是其中包含路由的代码,清单 1。调用此代码的代码是第二个源代码段,清单 2。我要转换为 XML 的 JSON 在清单 3 中. 从 Apache Camel 路由创建的 XML 在清单 4 中。但实际创建的 XML 不是 JSON 数据。 有谁知道如何使用 Apache Camel 将 JSON 转换为 XML?

package org.hai;

import org.apache.camel.builder.RouteBuilder;

/**
 * A Camel Java DSL Router
 */
public class MyRouteBuilder extends RouteBuilder {

    /**
     * Let's configure the Camel routing rules using Java code...
     */
    public void configure() {

        // Changes JSON data found in folder to XML - (hopefully) 
        from("file:src/data?noop=true").marshal().xstream().to("file:target/messages/others");
    }

}

清单 1:将 JSON 更改为 XML

的 Apache Camel 路由
package org.hai;

import org.apache.camel.main.Main;

/**
 * A Camel Application
 */
public class MainApp {

    /**
     * A main() so we can easily run these routing rules in our IDE
     */
    public static void main(String... args) throws Exception {
        Main main = new Main();
        main.enableHangupSupport();
        main.addRouteBuilder(new MyRouteBuilder());
        main.run(args);

        Thread.sleep(5000);

        System.exit(1);
    }

}

清单 2:调用 Apache Camel 路由的代码。

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

清单 3:JSON 转换为 XML

<?xml version='1.0' encoding='UTF-8'?>
<org.apache.camel.component.file.GenericFile>
<endpointPath>src/data</endpointPath>
<fileName>example.xml</fileName>
<fileNameOnly>example.xml</fileNameOnly>
<relativeFilePath>example.xml</relativeFilePath>
<absoluteFilePath>/home/captainkyle/Desktop/MavenPractice/transformer2/src/data/example.xml</absoluteFilePath>
<fileLength>583</fileLength>
<lastModified>1434061793000</lastModified>
<file class="file">src/data/example.xml</file>
<binding class="org.apache.camel.component.file.FileBinding"/>
<absolute>false</absolute>
<directory>false</directory>
</org.apache.camel.component.file.GenericFile>

清单 4:从上述 Camel 路由创建的 XML。

感谢您阅读本文。

此致,

您似乎缺少先将 json 文本转换为对象的步骤。例如,

from("file:src/data?noop=true").unmarshal().json(JsonLibrary.Jackson, Map.class).marshal().xstream().to("file:target/messages/others");

您可能希望转换为 POJO(而不是 Map)以避免难看的 xml 渲染。

您需要在应用程序依赖项中包含 camel-jackson 库(如果您愿意,也可以包含 camel-gson)。