如何使用 Apache Camel XmlJsonDataFormat 编组将 XML 字符串转换为 JSON 字符串

How to Convert XML string to JSON string using Apache Camel XmlJsonDataFormat marshalling

我正在尝试将下面程序中的 XML 字符串转换为 JSON 字符串。

我可以从文件中转换它,但不能从字符串中转换。

对此有什么想法吗?

package com.tda.topology;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import org.apache.camel.Exchange;   
import org.apache.camel.dataformat.xmljson.XmlJsonDataFormat;

public class Demo2 {

public static void main(String[] args) throws Exception {
    String xmlstring = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://services.web.post.list.com\"><soapenv:Header><authInfo xsi:type=\"soap:authentication\" xmlns:soap=\"http://list.com/services/SoapRequestProcessor\"><!--You may enter the following 2 items in any order--><username xsi:type=\"xsd:string\">user@email.com</username><password xsi:type=\"xsd:string\">password</password></authInfo></soapenv:Header></soapenv:Envelope>";
    XmlJsonDataFormat xmlJsonDataFormat = new XmlJsonDataFormat();
    xmlJsonDataFormat.setEncoding("UTF-8");
    xmlJsonDataFormat.setForceTopLevelObject(true);
    xmlJsonDataFormat.setTrimSpaces(true);
    xmlJsonDataFormat.setRootName("newRoot");
    xmlJsonDataFormat.setSkipNamespaces(true);
    xmlJsonDataFormat.setRemoveNamespacePrefixes(true);

    Exchange exchange;
    //exchange.setIn(in);

    InputStream stream = new ByteArrayInputStream(xmlstring.getBytes(StandardCharsets.UTF_8));
    //xmlJsonDataFormat.getSerializer().readFromStream(stream).toString();
    //xmlJsonDataFormat.marshal(exchange, graph, stream);

}
} 

您需要在您的 xmlJsonDataFormat 对象上调用 start 并将 xom jar 添加到您的 class 路径(如果它还不存在)。这对我有用:

xmlJsonDataFormat.start();
String json = xmlJsonDataFormat.getSerializer().readFromStream(stream).toString();

我通过查看源代码解决了这个问题。 getSerialiser 返回 null,因此我在 xmlJsonDataFormat 中搜索了序列化程序的初始化位置,这是通过在超级 class 的启动方法中调用的 doStart 方法完成的。

免责声明:不确定您是否应该像这样使用 XmlJsonDataFormat,它通常用于骆驼路线:from("direct:marshal").marshal(xmlJsonFormat).to("mock:json"); 但我不知道您的具体用例。