在Java中将XML转换为JSON或从JSON转换(无需额外的和元素)

我正在使用json-lib库中的XMLSerializer,以便在JSON和XML之间进行转换。

反正有没有避免生成的节点? 这是非常不方便地破坏路径表达式?

考虑以下示例:

 {"store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "JRR Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } }} 

序列化为:

     red 19.95    Nigel Rees reference 8.95 Sayings of the Century   Evelyn Waugh fiction 12.99 Sword of Honour   Herman Melville fiction 0-553-21311-3 8.99 Moby Dick   JRR Tolkien fiction 0-395-19395-8 22.99 The Lord of the Rings     

这个http://jsontoxml.utilities-online.info/所提供的东西正是我所追求的,但似乎没有Java版本。

您可以使用StAXON – JSON通过StAX执行此操作 。 StAXON实现了XML的Streaming API,但是可以读写JSON。 也就是说,您可以使用标准XML工具来完成Job。

复制XML的常见“技巧”是使用身份XML转换(XSLT)。

这是一些代码:

 InputStream input = ... // your JSON input; OutputStream output = System.out; try { /* * Create source. */ XMLInputFactory inputFactory = new JsonXMLInputFactory(); inputFactory.setProperty(JsonXMLInputFactory.PROP_MULTIPLE_PI, false); Source source = new StAXSource(inputFactory.createXMLStreamReader(input)); /* * Create result. */ XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); XMLStreamWriter writer = outputFactory.createXMLStreamWriter(output); writer = new PrettyXMLStreamWriter(writer); // format output Result result = new StAXResult(writer); /* * Transform (copy). */ TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.newTransformer().transform(source, result); } finally { /* * As per StAX specification, XMLStreamReader/Writer.close() doesn't close * the underlying stream. */ output.close(); input.close(); } 

用你的例子运行它会产生:

    reference Nigel Rees Sayings of the Century 8.95   fiction Evelyn Waugh Sword of Honour 12.99   fiction Herman Melville Moby Dick 0-553-21311-3 8.99   fiction JRR Tolkien The Lord of the Rings 0-395-19395-8 22.99   red 19.95   

注意:如果输出属性PROP_MULTIPLE_PI设置为true ,StAXON将生成处理指令。 当转换回JSON以触发数组启动时,StAXON可以使用这些。 如果您不需要返回JSON,请将此设置保留为false