0

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);

}
} 

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this is great It worked for me. I am trying to convert complex nested XML messages with name spaces in to Json. inside Real-time software like STORM.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.