[XML-DEV Mailing List Archive Home] [By Thread] [By Date] [Recent Entries] [Reply To This Message] xml to json converter
Hi all,
I've been playing around today, with this topic and thought of sharing my findings with people here. I wrote an XML to JSON converter, using following tools, 1. Little bit of java programming 2. JAXB 3. jackson-databind library This XML to JSON converter, works for particular XSD documents, and then can convert XML instance documents conforming to a specific XSD document to a JSON document. Below are the steps I followed, along with an example. 1) Write an XSD document Here's what I wrote for this example (named x1.xsd), <?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="X"> <xs:complexType> <xs:sequence> <xs:element name="a" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="b" type="xs:string" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="id" type="xs:integer"/> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> 2) Use JAXB command xjc as follows, xjc -d java_mapping -p com.example x1.xsd This generates following java files, ObjectFactory.java X.java 3) Write a java program as follows, import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class XmlToJsonConverter { public static void main(String[] args) { File xmlFile = new File(args[0]); // pass in an XML instance document file path try { JAXBContext jaxbContext = JAXBContext.newInstance(X.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); X x = (X)jaxbUnmarshaller.unmarshal(xmlFile); ObjectMapper objectMapper = new ObjectMapper(); String jsonStr = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(x); System.out.println(jsonStr); } catch (JAXBException ex) { ex.printStackTrace(); } catch (JsonProcessingException ex) { ex.printStackTrace(); } } } 4) Run the above java program, providing it the following XML instance document, <?xml version="1.0"?> <X> <a id="1"> <b>hello</b> <b>world</b> </a> <a id="2"> <b>I'm</b> <b>fine</b> </a> </X> The following JSON output is produced, { "a" : [ { "b" : [ "hello", "world" ], "id" : 1 }, { "b" : [ "I'm", "fine" ], "id" : 2 } ] } That's all about this. Any comments are welcome. Regards, Mukul Gandhi
[Date Prev] | [Thread Prev] | [Thread Next] | [Date Next] -- [Date Index] | [Thread Index] |
PURCHASE STYLUS STUDIO ONLINE TODAY!Purchasing Stylus Studio from our online shop is Easy, Secure and Value Priced! Download The World's Best XML IDE!Accelerate XML development with our award-winning XML IDE - Download a free trial today! Subscribe in XML format
|