使用Java将xml转换为json

有没有办法将xml文件转换为json? XML可以是任何结构,因此没有用于实例化的POJO类。 我需要将xml转换为json或转换为没有根节点的Map。

例如:

  Emil Example  
Example Blvd.
Example Ave.

预期的JSON

 { "firstName": "Emil", "lastName": "Example", "addresses": [ { "street" : "Example Blvd." }, { "street" : "Example Ave." } ] } 

 import org.json.JSONException; import org.json.JSONObject; import org.json.XML; XML.toJSONObject(xml_text).toString() 

org.json.XML

您可以使用json.org中的 JSON和XML库

 import org.json.JSONObject; import org.json.XML; import org.junit.Test; public class XmlToJsonTest { private static final String XML_TEXT = "\n" + "Tove\n" + "Jani\n" + "Reminder\n" + "Don't forget me this weekend!\n" + ""; private static final int PRETTY_PRINT_INDENT_FACTOR = 4; @Test public void convert() { JSONObject xmlJSONObj = XML.toJSONObject(XML_TEXT); String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR); System.out.println(jsonPrettyPrintString); } } 

资源

  Tove Jani Reminder Don't forget me this weekend!  

产量

 {"note": { "heading": "Reminder", "from": "Jani", "to": "Tove", "body": "Don't forget me this weekend!" }} 

如果您使用的是Java 8 ,则应该查看我的开源库: unXml 。 unXml基本上从Xpath映射到Json属性。

它可以在Maven Central上找到 。

 import com.fasterxml.jackson.databind.node.ObjectNode; import com.nerdforge.unxml.factory.ParsingFactory; import com.nerdforge.unxml.parsers.Parser; import org.w3c.dom.Document; public class ParserExample { public ObjectNode parseXml(String xml){ Parsing parsing = ParsingFactory.getInstance().create(); Document document = parsing.xml().document(xml); Parser parser = parsing.obj("//item") .attribute("firstName", "firstName") .attribute("lastName", "lastName") .attribute("addresses", parsing.arr("addresses/address", parsing.obj() .attribute("street", "street") )) .build(); ObjectNode result = parser.apply(document); return result; } } 

它将返回一个Jackson ObjectNode ,其中包含你的例子中的json。

在这个网站上,您可以找到一些有用的课程。

 public class Main { public static int PRETTY_PRINT_INDENT_FACTOR = 4; public static String TEST_XML_STRING = "Your xml string here"; public static void main(String[] args) { try { JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING); String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR); System.out.println(jsonPrettyPrintString); } catch (JSONException je) { System.out.println(je.toString()); } } } 

我使用的是JSON-java,但我发现更多Efficient Library将XML转换为JsonXmlToJson

这是从XML制作Json最佳定制

libary依赖项添加到APP build.gradle文件中

 dependencies { compile 'com.github.smart-fun:XmlToJson:1.4.4' // add this line } 

    James Bond Book for the dummies  
  • 自定义内容名称

     public String convertXmlToJson(String xml) { XmlToJson xmlToJson = new XmlToJson.Builder(xml) .setContentName("/library/book", "title") .build(); return xmlToJson.toString(); } 

     "library":{ "book":[ { "id":"007", "title":"James Bond" }, { "id":"000", "title":"Book for the dummies" } ] } } 

  • 自定义属性名称

     public String convertXmlToJson(String xml) { XmlToJson xmlToJson = new XmlToJson.Builder(xml) .setAttributeName("/library/book/id", "code") .build(); return xmlToJson.toString(); } 

     { "library":{ "book":[ { "code":"007", "content":"James Bond" }, { "code":"000", "content":"Book for the dummies" } ] } } 

和更有效的技术来定制你的Json

点击这里查看Github

您可以使用标准工具

  1. 使用jdk中的工具xjc 从schema生成Java类

    Java 9您必须使用–add-modules java.se.ee显式添加JAXB作为模块

  2. 使用Jackson以XML读写为JSON

使用https://schema.datacite.org/meta/kernel-4.1/metadata.xsd

1.使用jdk中的工具xjc

在我的示例中,我将使用基于datacite模式的相当复杂的示例。

 /path/to/jdk/bin/xjc -d /path/to/java/project \ -p stack24174963.datacite \ https://schema.datacite.org/meta/kernel-4.1/metadata.xsd 

这将回复

 parsing a schema... compiling a schema... stack24174963/datacite/Box.java stack24174963/datacite/ContributorType.java stack24174963/datacite/DateType.java stack24174963/datacite/DescriptionType.java stack24174963/datacite/FunderIdentifierType.java stack24174963/datacite/NameType.java stack24174963/datacite/ObjectFactory.java stack24174963/datacite/Point.java stack24174963/datacite/RelatedIdentifierType.java stack24174963/datacite/RelationType.java stack24174963/datacite/Resource.java stack24174963/datacite/ResourceType.java stack24174963/datacite/TitleType.java stack24174963/datacite/package-info.java 

2.使用Jackson以XML读写为JSON

  import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import stack24174963.datacite.Resource; public class HowToXmlToJsonWithSchema { @Test public void readXmlAndConvertToSchema() throws Exception { String example = "schemas/datacite/kernel-4.1/example/datacite-example-complicated-v4.1.xml"; try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(example)) { Resource resource = JAXB.unmarshal(in, Resource.class); System.out.println(asJson(resource)); } } private String asJson(Object obj) throws Exception { StringWriter w = new StringWriter(); new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true).writeValue(w, obj); String result = w.toString(); return result; } } 

打印:

  { "identifier" : { "value" : "10.5072/testpub", "identifierType" : "DOI" }, "creators" : { "creator" : [ { "creatorName" : { "value" : "Smith, John", "nameType" : "PERSONAL" }, "givenName" : "\nJohn", "familyName" : "\nSmith", "nameIdentifier" : [ ], "affiliation" : [ ] }, { "creatorName" : { "value" : "つまらないものですが", "nameType" : null }, "givenName" : null, "familyName" : null, "nameIdentifier" : [ { "value" : "0000000134596520", "nameIdentifierScheme" : "ISNI", "schemeURI" : "http://isni.org/isni/" } ], "affiliation" : [ ] } ] }, "titles" : { "title" : [ { "value" : "Właściwości rzutowań podprzestrzeniowych", "titleType" : null, "lang" : "pl" }, { "value" : "Translation of Polish titles", "titleType" : "TRANSLATED_TITLE", "lang" : "en" } ] }, "publisher" : "Springer", "publicationYear" : "2010", "resourceType" : { "value" : "Monograph", "resourceTypeGeneral" : "TEXT" }, "subjects" : { "subject" : [ { "value" : "830 German & related literatures", "subjectScheme" : "DDC", "schemeURI" : null, "valueURI" : null, "lang" : "en" }, { "value" : "Polish Literature", "subjectScheme" : null, "schemeURI" : null, "valueURI" : null, "lang" : "en" } ] }, "contributors" : { "contributor" : [ { "contributorName" : { "value" : "Doe, John", "nameType" : "PERSONAL" }, "givenName" : "\nJohn", "familyName" : "\nDoe", "nameIdentifier" : [ { "value" : "0000-0001-5393-1421", "nameIdentifierScheme" : "ORCID", "schemeURI" : "http://orcid.org/" } ], "affiliation" : [ ], "contributorType" : "DATA_COLLECTOR" } ] }, "dates" : null, "language" : "de", "alternateIdentifiers" : { "alternateIdentifier" : [ { "value" : "937-0-4523-12357-6", "alternateIdentifierType" : "ISBN" } ] }, "relatedIdentifiers" : { "relatedIdentifier" : [ { "value" : "10.5272/oldertestpub", "resourceTypeGeneral" : null, "relatedIdentifierType" : "DOI", "relationType" : "IS_PART_OF", "relatedMetadataScheme" : null, "schemeURI" : null, "schemeType" : null } ] }, "sizes" : { "size" : [ "256 pages" ] }, "formats" : { "format" : [ "pdf" ] }, "version" : "2", "rightsList" : { "rights" : [ { "value" : "Creative Commons Attribution-NoDerivs 2.0 Generic", "rightsURI" : "http://creativecommons.org/licenses/by-nd/2.0/", "lang" : null } ] }, "descriptions" : { "description" : [ { "content" : [ "\n Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea\n takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores\n et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.\n " ], "descriptionType" : "ABSTRACT", "lang" : "la" } ] }, "geoLocations" : null, "fundingReferences" : null } 

例如输入XML:

    10.5072/testpub   Smith, John John Smith   つまらないものですが 0000000134596520    Właściwości rzutowań podprzestrzeniowych Translation of Polish titles  Springer 2010  830 German & related literatures Polish Literature    Doe, John John Doe 0000-0001-5393-1421   de Monograph  937-0-4523-12357-6   10.5272/oldertestpub   256 pages   pdf  2  Creative Commons Attribution-NoDerivs 2.0 Generic    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.    すが    10.5072/testpub   Smith, John John Smith   つまらないものですが 0000000134596520    Właściwości rzutowań podprzestrzeniowych Translation of Polish titles  Springer 2010  830 German & related literatures Polish Literature    Doe, John John Doe 0000-0001-5393-1421   de Monograph  937-0-4523-12357-6   10.5272/oldertestpub   256 pages   pdf  2  Creative Commons Attribution-NoDerivs 2.0 Generic    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.    

有静态方法xmlToJson的下划线-java库。 我是该项目的维护者。 实例

 import com.github.underscore.lodash.U; public class Main { public static void main(String[] args) { final String xml = "\n\n" + " 1\n 2\n"; System.out.println(U.xmlToJson(xml)); } }