[英]How to Convert XML string to JSON string using Apache Camel XmlJsonDataFormat marshalling
I am trying to convert XML String in the below program to JSON String. 我正在尝试将以下程序中的XML String转换为JSON String。
I am able to convert it from file but not from the string. 我能够从文件而不是从字符串转换它。
Any idea about this? 有什么想法吗?
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);
}
}
You need to call start on your xmlJsonDataFormat object and add xom jar to your class path (if it's not already there). 您需要在xmlJsonDataFormat对象上调用start,然后将xom jar添加到您的类路径(如果尚不存在)。 This is what worked for me: 这对我有用:
xmlJsonDataFormat.start();
String json = xmlJsonDataFormat.getSerializer().readFromStream(stream).toString();
I was able to work this out through looking in the source. 通过查看源代码,我能够解决这个问题。 getSerialiser was returning null and so I searched in xmlJsonDataFormat for where the serializer was initialised and it's done so by the doStart method which is called in the super class's start method. getSerialiser返回的是null,因此我在xmlJsonDataFormat中搜索了初始化序列化程序的位置,并通过在超类的start方法中调用的doStart方法完成了初始化。
Disclaimer: not sure you're supposed to use XmlJsonDataFormat like this, it's usually meant for use in a camel route: from("direct:marshal").marshal(xmlJsonFormat).to("mock:json");
免责声明:不确定您是否应该像这样使用XmlJsonDataFormat,它通常是用于骆驼路线的: from("direct:marshal").marshal(xmlJsonFormat).to("mock:json");
but I don't know your specific use case. 但我不知道您的特定用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.