使用这个工具;我遇到了你描述的同样的问题。我们用来让它工作的解决方案是将我们的 Maven 依赖项从 Jackson 更改为 json-lib。我们使用这个网站作为指南:
如果使用 maven,请向您的 pom 添加依赖项。
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.3</version>
<type>jar</type>
<classifier>jdk15</classifier>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>xom</groupId>
<artifactId>xom</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
将此 xml 保存在示例文件 sample-xml.xml 中
<?xml version="1.0" encoding="UTF-8"?>
<important-data certified="true" processed="true">
<timestamp>232423423423</timestamp>
<authors>
<author>
<firstName>Tim</firstName>
<lastName>Leary</lastName>
</author>
</authors>
<title>Flashbacks</title>
<shippingWeight>1.4 pounds</shippingWeight>
<isbn>978-0874778700</isbn>
</important-data>
主班
package com.discursive.answers;
import java.io.InputStream;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.io.IOUtils;
public class ConvertXMLtoJSON {
public static void main(String[] args) throws Exception {
InputStream is =
ConvertXMLtoJSON.class.getResourceAsStream("sample-xml.xml");
String xml = IOUtils.toString(is);
XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read( xml );
System.out.println( json.toString(2) );
}
}
结果
{
"@certified": "true",
"@processed": "true",
"timestamp": "232423423423",
"authors": [ {
"firstName": "Tim",
"lastName": "Leary"
}],
"title": "Flashbacks",
"shippingWeight": "1.4 pounds",
"isbn": "978-0874778700"
}