为什么这个Apache Camel路由不会将JSON转换为XML?

时间:2015-06-12 15:17:10

标签: java json xml apache-camel

我正在尝试使用Apache Camel路由将一些JSON转换为XML。下面是包含其中路由的代码,列出1.调用此代码的代码是第二个源代码段,列出2.我想要转换为XML的JSON在清单3中。从中创建的XML Apache Camel路由在清单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:要转换为XML的JSON

<?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。

感谢您阅读本文。

此致

1 个答案:

答案 0 :(得分:2)

看起来你错过了第一次将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)。