jaxb xsd生成xml
在本文中,我演示了一种从XML Schema (XSD)生成JSON Schema的 方法 。 在概述从XML Schema创建JSON Schema的方法的同时,本文还演示了JAXB实现的使用(与JDK 9捆绑在一起的xjc版本2.2.12-b150331.1824 [build 1.9.0-ea-b68])和JSON / Java绑定实现的说明( 杰克逊 2.5.4)。
从XSD生成JSON模式的这种方法的步骤可以概括为:
- 应用JAXB的xjc编译器从XML Schema(XSD)生成Java类。
- 应用Jackson来从JAXB生成的Java类生成JSON模式。
使用JAXB的xjc从XSD生成Java类
为了便于讨论,我将使用我先前的博客文章A JAXB Nuance:字符串与枚举受限XSD字符串中的枚举使用的简单Food.xsd
。 为了方便起见,我在此处重现了该简单模式,但没有特定于先前博客文章的XML注释:
Food.xsd
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:dustin="http://marxsoftware.blogspot.com/foodxml"
targetNamespace="http://marxsoftware.blogspot.com/foodxml"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xs:element name="Food">
<xs:complexType>
<xs:sequence>
<xs:element name="Vegetable" type="dustin:Vegetable" />
<xs:element ref="dustin:Fruit" />
<xs:element name="Dessert" type="dustin:Dessert" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:simpleType name="Vegetable">
<xs:restriction base="xs:string">
<xs:enumeration value="Carrot"/>
<xs:enumeration value="Squash"/>
<xs:enumeration value="Spinach"/>
<xs:enumeration value="Celery"/>
</xs:restriction>
</xs:simpleType>
<xs:element name="Fruit">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Watermelon"/>
<xs:enumeration value="Apple"/>
<xs:enumeration value="Orange"/>
<xs:enumeration value="Grape"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:simpleType name="Dessert">
<xs:restriction base="xs:string">
<xs:enumeration value="Pie"/>
<xs:enumeration value="Cake"/>
<xs:enumeration value="Ice Cream"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
使用由JDK提供的JAXB实现提供的xjc命令行工具来生成与此XSD相对应的Java类很容易。 下一个屏幕快照使用以下命令显示了此过程:
xjc -d jaxb。\ Food.xsd
这个简单的命令生成与提供的Food.xsd
相对应的Java类,并将这些类放置在指定的“ jaxb”子目录中。
用Jackson从JAXB生成的类生成JSON
使用现在可用的JAXB生成的类,可以将