【问题标题】:create json from dom document从 dom 文档创建 json
【发布时间】:2011-07-20 12:17:37
【问题描述】:

我有一个 org.w3c.dom.Document。 生成xml是没有问题的。 但是如何从文档中生成 json 呢?

这是获取xml字符串的代码

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.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();

【问题讨论】:

    标签: java xml json


    【解决方案1】:

    JSON 和 XML 的数据模型不同,因此没有从 XML 到 JSON 的规范转换。

    如果你能提供你的数据,也许我们可以提出一些建议。

    【讨论】:

    • 实际上,我使用三重存储(大师)的数据构建了 dom 文档。我没有任何数据对象,因为 dom 是根据 sparql 查询的结果动态构建的。我不想拥有静态数据对象。
    • 问题是关于你的数据格式......例如您希望从中获得的 XML 和 JSON 示例可能会有所帮助。
    【解决方案2】:

    只是为了解决这个问题。 最后我使用了不同的方法。 我将数据保存在树中。

    然后为了渲染 JSONView,我使用了 JacksonJsonView 映射器。 为了呈现 XML,我使用了 XML Marshaller。

    【讨论】:

    【解决方案3】:

    XmlMapper xmlMapper = new XmlMapper();

    String xml= FileUtils.readFileToString(new File("test_4.xsd.xml"),Charset.defaultCharset());

    JsonNode 节点 = xmlMapper.readTree(xml.getBytes());

    ObjectMapper jsonMapper = new ObjectMapper();

    字符串 json = jsonMapper.writeValueAsString(node);

    System.out.println(json);

    Reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-30
      • 2012-03-24
      • 1970-01-01
      • 2013-04-04
      • 2010-11-26
      相关资源
      最近更新 更多