实体类JavaBean转Xml-JAXB的使用分享

1 篇文章 0 订阅

近期工作中遇到这样的需求,接口返回值要求Xml格式,其实接口就是实现展示一个实体类的所有属性(字段)的信息,那么问题就转化为如何将一个实体类JavaBean转化为xml格式返回。搜了一下,发现Java提供了现成的类来处理此类问题-JAXB。百度:JAXB能够使用Jackson对JAXB注解的支持实现(jackson-module-jaxb-annotations),既方便生成XML,也方便生成JSON,这样一来可以更好的标志可以转换为JSON对象的JAVA类。JAXB允许JAVA人员将JAVA类映射为XML表示方式。

下面主要记录一下用到的一些方法、技巧,备忘。

首先是JavaBean的注解:

@XmlRootElement

类注解,声明xml的根元素。

@XmlAccessorType

控制通过哪种方式识别将要转化为xml的JavaBean的属性。共有四种取值:
XmlAccessType.FIELD : JavaBean中的所有成员变量
XmlAccessType.PROPERTY : JavaBean中所有通过getter/setter方式访问的成员变量
XmlAccessType.PUBLIC_MEMBER : JavaBean中所有的public访问权限的成员变量和通过getter/setter方式访问的成员变量
XmlAccessType.NONE : JavaBean中所有属性都不映射为xml的元素,只通过注解识别

@XmlType

propOrder={}属性定义xml元素的排列顺序,注意必须列出JavaBean的所有属性。

@XmlTransient

声明此属性不转化为xml的元素。

@XmlJavaTypeAdapter

自定义实现负责对象的转化,例如日期(Date)类型。

@XmlElement

声明某属性为xml的元素,可通过name属性控制元素名称。

@XmlElementWrapper

适用于数组属性,转化为xml时可在数组元素外包一个元素。

@XmlAttribute

把JavaBean的属性转化为xml某元素的属性。

其次是具体实现转化的代码:

public static void main(String[] args) {
    Device device = new Device();               
    String ret = JAXBUtil.marshal(device);
}
public class JAXBUtil {
    public static String marshal(Object obj) {
        try {
            StringWriter sw = new StringWriter();
            JAXBContext context = JAXBCache.instance().getJAXBContext(obj.getClass());
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.setProperty(Marshaller.JAXB_FRAGMENT, true);// 是否省略xm头声明信息
            m.marshal(obj, sw);
            return sw.toString();
        } catch(JAXBException e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}

最后给一个JavaBean的例子和转化结果:

@XmlRootElement(name = "device")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder= {"deviceRecordStatus", "devicePublishDate", "deviceCommDistributionEndDate", "deviceCommDistributionStatus", "identifiers",
        "brandName", "versionModelNumber", "catalogNumber", "companyName", "deviceCount", "deviceDescription", "DMExempt", "premarketExempt",
        "deviceHCTP", "deviceKit", "deviceCombinationProduct", "singleUse", "lotBatch", "serialNumber", "manufacturingDate", "expirationDate", 
        "donationIdNumber", "labeledContainsNRL", "labeledNoNRL", "MRISafetyStatus", "rx", "otc", "contacts", "gmdnTerms", "productCodes", "deviceSize", 
        "storageHandling", "sterilization", "specification", "executeStandard"})
public class Device extends BaseVo{
    // 器械标识
    @XmlTransient
    @JSONField(serialize = false)
    private String primaryDi;
    // 器械记录状态
    private String deviceRecordStatus;
    // 发布日期
    @XmlJavaTypeAdapter(JAXBDateAdapter.class)
    private Date devicePublishDate;
    // 商业分销结束日期
    @XmlElement(nillable=true)
    private String deviceCommDistributionEndDate;
    // 商业分销状态
    @XmlElement(nillable=true)
    private String deviceCommDistributionStatus;
    // 商标名
    private String brandName;
    // 版本/型号
    private String versionModelNumber;
    // 目录号
    @XmlElement(nillable=true)
    private String catalogNumber;
    // 公司名称
    private String companyName;
    // 器械计数
    @XmlElement(nillable=true)
    private Integer deviceCount;
    // 器械描述
    @XmlElement(nillable=true)
    private String deviceDescription;
    // 需直接标记,但可豁免
    @XmlElement(nillable=true)
    private Boolean DMExempt;
    // 上市前提交器械豁免
    @XmlElement(nillable=true)
    private Boolean premarketExempt;
    // 人类细胞,组织,或细胞或组织为基础的产品(HCT/P)
    @XmlElement(nillable=true)
    private Boolean deviceHCTP;
    // 是否套装
    @XmlElement(nillable=true)
    private Boolean deviceKit;
    // 是否组合产品
    @XmlElement(nillable=true)
    private Boolean deviceCombinationProduct;
    // 一次性使用
    @XmlElement(nillable=true)
    private Boolean singleUse;
    // 批号
    @XmlElement(nillable=true)
    private Boolean lotBatch;
    // 序列号
    @XmlElement(nillable=true)
    private Boolean serialNumber;
    // 生产日期
    @XmlElement(nillable=true)
    private Boolean manufacturingDate;
    // 失效日期
    @XmlElement(nillable=true)
    private Boolean expirationDate;
    // 捐献ID号
    @XmlElement(nillable=true)
    private Boolean donationIdNumber;
    // 器械需要标记含有天然橡胶乳胶或干燥的天然乳胶(21 CFR 801.437)
    @XmlElement(nillable=true)
    private Boolean labeledContainsNRL;
    // 器械标记“不含天然橡胶乳胶”
    @XmlElement(nillable=true)
    private Boolean labeledNoNRL;
    // MRI安全性
    @XmlElement(nillable=true)
    private String MRISafetyStatus;
    // 处方使用
    @XmlElement(nillable=true)
    private Boolean rx;
    // 非处方
    @XmlElement(nillable=true)
    private Boolean otc;

    // 器械标识
    private Identifiers identifiers;        // 器械标识(DI),器械类型,发布机构,包装包含DI号,每包装数量,包装中止日期,包装状态
    // 客户信息
    private Contacts contacts;  // 客户电话,客户座机,客户电子邮件
    // 全球医疗器械命名
    private GmdnTerms gmdnTerms;    // 名称,定义
    // FDA信息
    private ProductCodes productCodes;  // fda产品码,fda产品名称
    // 尺寸信息
    @XmlElementWrapper(name = "deviceSizes")
    private List<DeviceSize> deviceSize;    // 尺寸类型,尺寸值,尺寸测量单位,尺寸类型文本
    // 贮存和操作
    @XmlElementWrapper(name = "environmentalConditions")
    private List<StorageHandling> storageHandling;  // 贮存和操作类型,高值,高值单位,低值,低值单位,特殊存储条件
    // 消毒
    private Sterilization sterilization;    // 是否无菌包装,使用前需要灭菌,灭菌方式

    // 省略getter setter
    // 省略部分类的声明
}
    <device xmlns="http://www.fda.gov/cdrh/gudid" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <deviceRecordStatus>Published</deviceRecordStatus>
        <devicePublishDate>2017-07-31</devicePublishDate>
        <deviceCommDistributionEndDate xsi:nil="true"/>
        <deviceCommDistributionStatus>In Commercial Distribution</deviceCommDistributionStatus>
        <identifiers>
            <identifier>
                <deviceId>08717648200274</deviceId>
                <deviceIdType>Primary</deviceIdType>
                <deviceIdIssuingAgency>GS1</deviceIdIssuingAgency>
                <containsDINumber xsi:nil="true"/>
                <pkgQuantity xsi:nil="true"/>
                <pkgDiscontinueDate xsi:nil="true"/>
                <pkgStatus xsi:nil="true"/>
                <pkgType xsi:nil="true"/>
            </identifier>
        </identifiers>
        <brandName>XIENCE ALPINE</brandName>
        <versionModelNumber>1145350-28</versionModelNumber>
        <catalogNumber>1145350-28</catalogNumber>
        <companyName>ABBOTT VASCULAR INC.</companyName>
        <deviceCount>1</deviceCount>
        <deviceDescription>XIENCE Alpine Everolimus Eluting Coronary Stent System 3.50 mm x 28 mm / Over-The-Wire</deviceDescription>
        <DMExempt>false</DMExempt>
        <premarketExempt>false</premarketExempt>
        <deviceHCTP>false</deviceHCTP>
        <deviceKit>false</deviceKit>
        <deviceCombinationProduct>true</deviceCombinationProduct>
        <singleUse>true</singleUse>
        <lotBatch>true</lotBatch>
        <serialNumber>false</serialNumber>
        <manufacturingDate>false</manufacturingDate>
        <expirationDate>true</expirationDate>
        <donationIdNumber>false</donationIdNumber>
        <labeledContainsNRL>false</labeledContainsNRL>
        <labeledNoNRL>false</labeledNoNRL>
        <MRISafetyStatus>MR Conditional</MRISafetyStatus>
        <rx>true</rx>
        <otc>false</otc>
        <contacts>
            <customerContact>
                <phone>+1(800)227-9902</phone>
                <phoneExtension xsi:nil="true"/>
                <email>AV.CUSTOMERCARE@AV.ABBOTT.COM</email>
            </customerContact>
        </contacts>
        <gmdnTerms>
            <gmdn>
                <gmdnPTName>Drug-eluting coronary artery stent, non-bioabsorbable-polymer-coated</gmdnPTName>
                <gmdnPTDefinition>A sterile non-bioabsorbable metal tubular mesh structure covered with a non-bioabsorbable polymer and a drug coating that is designed to be implanted, via a delivery catheter, into a coronary artery (or saphenous vein graft) to maintain its patency typically in a patient with symptomatic atherosclerotic heart disease. The drug coating is slowly released and intended to inhibit restenosis by reducing vessel smooth muscle cell proliferation. Disposable devices associated with implantation may be included.</gmdnPTDefinition>
            </gmdn>
        </gmdnTerms>
        <productCodes>
            <fdaProductCode>
                <productCode>NIQ</productCode>
                <productCodeName>Coronary drug-eluting stent</productCodeName>
            </fdaProductCode>
        </productCodes>
        <environmentalConditions>
            <storageHandling>
                <storageHandlingType>Handling Environment Temperature</storageHandlingType>
                <storageHandlingHigh value="30" unit="Degrees Celsius"/>
                <storageHandlingLow value="15" unit="Degrees Celsius"/>
                <storageHandlingSpecialConditionText xsi:nil="true"/>
            </storageHandling>
            <storageHandling>
                <storageHandlingType>Special Storage Condition, Specify</storageHandlingType>
                <storageHandlingHigh value="" unit=""/>
                <storageHandlingLow value="" unit=""/>
                <storageHandlingSpecialConditionText>Store in a dry, dark, cool place. Protect from light. Store at 25 degrees C; excursions between 15 to 30 degrees C permitted.</storageHandlingSpecialConditionText>
            </storageHandling>
            <storageHandling>
                <storageHandlingType>Storage Environment Temperature</storageHandlingType>
                <storageHandlingHigh value="25" unit="Degrees Celsius"/>
                <storageHandlingLow value="25" unit="Degrees Celsius"/>
                <storageHandlingSpecialConditionText xsi:nil="true"/>
            </storageHandling>
        </environmentalConditions>
        <sterilization>
            <deviceSterile>true</deviceSterile>
            <sterilizationPriorToUse>false</sterilizationPriorToUse>
            <methodTypes/>
        </sterilization>
    </device>
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值