create json from dom document
I have a org.w3c.dom.Document. To generate the xml is no problem. But how can I generate json out of the document ?
this is the code to get the xml string
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(Output开发者_运维技巧Keys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
// create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(document);
trans.transform(source, result);
String xmlString = sw.toString();
The data models for JSON and XML are different, therefore there is no canonical transformation from XML to JSON.
If you could present your data, maybe we can propose something.
Just to solve this question. At the end I used a different approach. I saved the data in a Tree.
Then for Rendering the JSONView I used the JacksonJsonView Mapper. And for Rendering the XML I used an XML Marshaller.
XmlMapper xmlMapper = new XmlMapper();
String xml= FileUtils.readFileToString(new File("test_4.xsd.xml"),Charset.defaultCharset());
JsonNode node = xmlMapper.readTree(xml.getBytes());
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(node);
System.out.println(json);
Reference
精彩评论