使用Java将xml转换为json
有没有办法将xml文件转换为json?XML可以是任何结构,因此没有用于实例化的POJO类。我需要将xml转换为json或映射,而不需要根节点 例如:使用Java将xml转换为json,java,xml,json,Java,Xml,Json,有没有办法将xml文件转换为json?XML可以是任何结构,因此没有用于实例化的POJO类。我需要将xml转换为json或映射,而不需要根节点 例如: <import name="person"> <item> <firstName>Emil</firstName> <lastName>Example</lastName> <addresses>
<import name="person">
<item>
<firstName>Emil</firstName>
<lastName>Example</lastName>
<addresses>
<address>
<street>Example Blvd.</street>
</address>
<address>
<street>Example Ave.</street>
</address>
</addresses>
</item>
</import>
在这方面,您可以找到一些对您的任务有用的类(在页面底部的java部分)
您可以从中使用JSON和XML库
如果您使用的是Java8,您应该查看我的开源库:。unXml基本上从XPath映射到Json属性 可以在网上买到 范例
import com.fasterxml.jackson.databind.node.ObjectNode;
导入com.nerdforge.unxml.factory.ParsingFactory;
导入com.nerdforge.unxml.parsers.Parser;
导入org.w3c.dom.Document;
公共类解析示例{
公共对象节点解析xml(字符串xml){
解析=ParsingFactory.getInstance().create();
Document Document=parsing.xml().Document(xml);
Parser Parser=parsing.obj(“//项”)
.attribute(“firstName”、“firstName”)
.attribute(“lastName”、“lastName”)
.attribute(“addresses”,parsing.arr(“addresses/address”,parsing.obj())
.属性(“街道”、“街道”)
))
.build();
ObjectNode结果=parser.apply(文档);
返回结果;
}
}
它将返回一个带有示例中json的ObjectNode
。库具有静态方法U.xmlToJson(xml)
导入com.github.underline.lodash.U;
公共班机{
公共静态void main(字符串[]args){
最终字符串xml=“\n\n”
+“1\n 2\n”;
System.out.println(U.xmlToJson(xml));
}
}
我被使用过,但我发现将XML
转换为Json
更有效的库是
从XML
将libary
依赖项添加到应用程序build.gradle
文件中
dependencies {
compile 'com.github.smart-fun:XmlToJson:1.4.4' // add this line
}
- 自定义属性名称
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;
}
}
您可以为其使用标准工具
xjc
,
由于Java9
必须使用显式地添加JAXB作为模块–添加模块Java.se.ee
见:
xjc
XML
写出为JSON
使用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" : "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<givenName xmlns=\"http://datacite.org/schema/kernel-4\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">John</givenName>",
"familyName" : "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<familyName xmlns=\"http://datacite.org/schema/kernel-4\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">Smith</familyName>",
"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" : "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<givenName xmlns=\"http://datacite.org/schema/kernel-4\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">John</givenName>",
"familyName" : "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<familyName xmlns=\"http://datacite.org/schema/kernel-4\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">Doe</familyName>",
"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
}
{
“标识符”:{
“值”:“10.5072/testpub”,
“标识符类型”:“DOI”
},
“创造者”:{
“创建者”:[{
“creatorName”:{
“价值”:“史密斯,约翰”,
“名称类型”:“个人”
},
“givenName”:“\nJohn”,
“familyName”:“\n提交”,
“名称标识符”:[],
“从属关系”:[]
}, {
“creatorName”:{
“值”:つまらないものですが",
“nameType”:空
},
“givenName”:空,
“familyName”:空,
“名称标识符”:[{
“值”:“0000000 134596520”,
“名称标识方案”:“ISNI”,
“方案”:http://isni.org/isni/"
} ],
“从属关系”:[]
} ]
},
“头衔”:{
“标题”:[{
“价值”:“Właściwości rzutowańpodprzestrzeniowych”,
“标题类型”:空,
“lang”:“pl”
}, {
“价值”:“波兰语标题的翻译”,
“标题类型”:“翻译的标题”,
“郎”:“恩”
} ]
},
“出版商”:“斯普林格”,
“出版年”:“2010年”,
“资源类型”:{
“价值”:“专论”,
“resourceTypeGeneral”:“文本”
},
“主题”:{
“主题”:[{
“价值”:“830篇德国及相关文献”,
“主题方案”:“DDC”,
“schemeURI”:空,
“valueURI”:null,
“郎”:“恩”
}, {
“价值”:“波兰文学”,
“subjectScheme”:空,
“schemeURI”:空,
“valueURI”:null,
“郎”:“恩”
} ]
},
“贡献者”:{
“投稿人”:[{
“出资人姓名”:{
“价值”:“多伊,约翰”,
“名称类型”:“个人”
},
“givenName”:“\nJohn”,
“familyName”:“\nDoe”,
“名称标识符”:[{
“值”:“0000-0001-5393-1421”,
“名称标识模式”:“ORCID”,
“方案”:http://orcid.org/"
} ],
“附属关系”:[],
“参与者类型”:“数据采集器”
} ]
},
“日期”:空,
“语言”:“德”,
“替代标识符”:{
“替代标识符”:[{
“值”:“937-0-4523-12357-6”,
“alternateIdentifierType”:“ISBN”
} ]
},
“相关标识符”:{
“关联标识符”:[{
“价值”:“10.5272/oldertestpub”,
“resourceTypeGeneral”:空,
“relatedIdentifierType”:“DOI”,
“关系类型”:“是的一部分”,
“relatedMetadataScheme”:null,
“schemeURI”:空,
“schemeType”:null
} ]
},
“尺寸”:{
“大小”:[“256页”]
},
“格式”:{
“格式”:[“pdf”]
},
“五
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<ObjectNode> 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;
}
}
import com.github.underscore.lodash.U;
public class Main {
public static void main(String[] args) {
final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n"
+ " <FirstItem>1</FirstItem>\n <SecondItem>2</SecondItem>\n</root>";
System.out.println(U.xmlToJson(xml));
}
}
dependencies {
compile 'com.github.smart-fun:XmlToJson:1.4.4' // add this line
}
<?xml version="1.0" encoding="utf-8"?>
<library>
<book id="007">James Bond</book>
<book id="000">Book for the dummies</book>
</library>
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"
}
]
}
}
/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
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" : "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<givenName xmlns=\"http://datacite.org/schema/kernel-4\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">John</givenName>",
"familyName" : "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<familyName xmlns=\"http://datacite.org/schema/kernel-4\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">Smith</familyName>",
"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" : "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<givenName xmlns=\"http://datacite.org/schema/kernel-4\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">John</givenName>",
"familyName" : "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<familyName xmlns=\"http://datacite.org/schema/kernel-4\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">Doe</familyName>",
"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 version="1.0" encoding="UTF-8"?>
<resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://datacite.org/schema/kernel-4" xsi:schemaLocation="http://datacite.org/schema/kernel-4 http://schema.datacite.org/meta/kernel-4.1/metadata.xsd">
<identifier identifierType="DOI">10.5072/testpub</identifier>
<creators>
<creator>
<creatorName nameType="Personal">Smith, John</creatorName>
<givenName>John</givenName>
<familyName>Smith</familyName>
</creator>
<creator>
<creatorName>つまらないものですが</creatorName>
<nameIdentifier nameIdentifierScheme="ISNI" schemeURI="http://isni.org/isni/">0000000134596520</nameIdentifier>
</creator>
</creators>
<titles>
<title xml:lang="pl">Właściwości rzutowań podprzestrzeniowych</title>
<title xml:lang="en" titleType="TranslatedTitle">Translation of Polish titles</title>
</titles>
<publisher>Springer</publisher>
<publicationYear>2010</publicationYear>
<subjects>
<subject xml:lang="en" subjectScheme="DDC">830 German & related literatures</subject>
<subject xml:lang="en">Polish Literature</subject>
</subjects>
<contributors>
<contributor contributorType="DataCollector">
<contributorName nameType="Personal">Doe, John</contributorName>
<givenName>John</givenName>
<familyName>Doe</familyName>
<nameIdentifier nameIdentifierScheme="ORCID" schemeURI="http://orcid.org/">0000-0001-5393-1421</nameIdentifier>
</contributor>
</contributors>
<language>de</language>
<resourceType resourceTypeGeneral="Text">Monograph</resourceType>
<alternateIdentifiers>
<alternateIdentifier alternateIdentifierType="ISBN">937-0-4523-12357-6</alternateIdentifier>
</alternateIdentifiers>
<relatedIdentifiers>
<relatedIdentifier relatedIdentifierType="DOI" relationType="IsPartOf">10.5272/oldertestpub</relatedIdentifier>
</relatedIdentifiers>
<sizes>
<size>256 pages</size>
</sizes>
<formats>
<format>pdf</format>
</formats>
<version>2</version>
<rightsList>
<rights rightsURI="http://creativecommons.org/licenses/by-nd/2.0/">Creative Commons Attribution-NoDerivs 2.0 Generic</rights>
</rightsList>
<descriptions>
<description xml:lang="la" descriptionType="Abstract">
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.
</description>
</descriptions>
</resource>