使用的相关包
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20211205</version>
</dependency>
遇到的问题 NoSuchMethodError
解决方案: https://stackoverflow.com/questions/52371365/nosuchmethod-error-when-using-org-json-to-convert-xml-to-json
Exception in thread "main" java.lang.NoSuchMethodError: org.json.JSONTokener.<init>(Ljava/io/Reader;)V
at org.json.XMLTokener.<init>(XMLTokener.java:57)
at org.json.XML.toJSONObject(XML.java:675)
at org.json.XML.toJSONObject(XML.java:733)
at org.json.XML.toJSONObject(XML.java:602)
at com.example.demo.TestXml.test2(TestXml.java:21)
at com.example.demo.TestXml.main(TestXml.java:17)
案例
// xml 转换为 json
XMLSerializer xmlSerializer = new XMLSerializer();
JSON read = xmlSerializer.read(xml);
System.out.println(read.toString());
// json 转换为 xml
String write = xmlSerializer.write(read);
System.out.println(write);