Reputation: 404
I am trying to convert XML String in the below program to 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\">[email protected]</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);
}
}
Upvotes: 0
Views: 3053
Reputation: 756
You need to call start on your xmlJsonDataFormat object and add xom jar to your class path (if it's not already there). 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.
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");
but I don't know your specific use case.
Upvotes: 4