1. 程式人生 > >JAXB實現xml與物件互相轉換

JAXB實現xml與物件互相轉換

不需要引入任何外部jar包,JAXB自jdk1.5就已被整合,jdk1.7已升級為JAXB2。

1.xml報文

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="urn:iso:std:iso:20022:tech:xsd:pacs.008.001.02">
    <MsgHeader>
        <SndDt>2017-01-01T14:21:21</SndDt>
        <MsgTp>epcc.201.001.01</MsgTp>
        <IssrId>31310000001311</IssrId>
        <Drctn>11</Drctn>
        <SignSN>313100000013</SignSN>
        <NcrptnSN>313100000013</NcrptnSN>
        <DgtlEnvlp>asdjjnfsaskjdjgf;lasnlfklsadfosadnfbjhsafnlsdbfsafntrgnidfnjkugfbgdlkgnui</DgtlEnvlp>
    </MsgHeader>
    <MsgBody>
        <PyerInf>
            <PyerAcctIssrId>C1010411000013</PyerAcctIssrId>
            <PyerAcctTp>00</PyerAcctTp>
            <SgnNo>130073386132613885</SgnNo>
            <PyerTrxTrmTp>02</PyerTrxTrmTp>
            <PyerTrxTrmNo>F93P72HCFR9M</PyerTrxTrmNo>
        </PyerInf>
        <PyerTrxTrmNo>1</PyerTrxTrmNo>
        <PyeeInf>
            <PyeeAcctIssrId>C1010411000013</PyeeAcctIssrId>
            <PyeeAcctId>282704424720582705</PyeeAcctId>
            <PyeeAcctNm>

[email protected]</PyeeAcctNm>
            <PyeeAcctTp>04</PyeeAcctTp>
            <PyeeAcctTp>CN</PyeeAcctTp>
            <PyeeAcctTp>110102</PyeeAcctTp>
            <PyerTrxTrmTp>06</PyerTrxTrmTp>
            <PyerTrxTrmNo>1D6AP1500</PyerTrxTrmNo>
        </PyeeInf>
        <ResfdtInf>
            <InstgAcctId>1001278619005510977</InstgAcctId>
            <InstgAcctNm>客戶備付金</InstgAcctNm>
            <ResfdAcctIssrId>C1010511003703</ResfdAcctIssrId>
        </ResfdtInf>
        <TrxInf>
            <TrxId>20170518654321098765432100010205</TrxId>
            <TrxDtTm>2017-05-19T01:18:23</TrxDtTm>
            <TrxAmt>CNY175.19</TrxAmt>
            <TrxCtgy>0110</TrxCtgy>
            <BizTp>100002</BizTp>
            <AcctInTp>02</AcctInTp>
        </TrxInf>
        <OrdrInf>
            <TrxId>20170518100615209112</TrxId>
            <TrxDtTm>2|2|chd%07515|</TrxDtTm>
            <TrxAmt>batpay</TrxAmt>
        </OrdrInf>
        <BatchId>B201705180016</BatchId>
        <TrxDevcInf>140.205.112.1|F0E1D2C3B4A5||||||</TrxDevcInf>
    </MsgBody>
</root>

 2.利用trang.jar自動生成對應的javabean,trang.jar下載地址:https://download.csdn.net/download/shenszy/10673076,生成的javabean需更改註解並修改package-info.java檔案。也可手寫javabean。修改後物件及package-info.java檔案見下方程式碼:

Root.java

@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.NONE)
public class Root {

    @XmlElement(name = "MsgHeader")
    private MsgHeader MsgHeader;

    @XmlElement(name = "MsgBody")
    private MsgBody MsgBody;

    //get,set省略……
}

MsgHeader.java

@XmlRootElement(name = "MsgHeader")
@XmlAccessorType(XmlAccessType.NONE)
public class MsgHeader {
    @XmlElement(name = "SndDt")
    private String sndDt;

    @XmlElement(name = "MsgTp")
    private String msgTp;

    @XmlElement(name = "IssrId")
    private String issrId;

    @XmlElement(name = "Drctn")
    private String drctn;

    @XmlElement(name = "SignSN")
    private String signSn;

    @XmlElement(name = "NcrptnSN")
    private String ncrptnSN;

    @XmlElement(name = "DgtlEnvlp")
    private String dgtlEnvlp;

    //get,set省略……
}

MsgBody.java

@XmlRootElement(name = "MsgBody")
@XmlAccessorType(XmlAccessType.NONE)
public class MsgBody {

    @XmlElement(name = "PyerInf")
    private PyerInf pyerInf;//付款方資訊

    @XmlElement(name = "PyerTrxTrmNo")
    private String pyerTrxTrmNo;//收付標識,1:付款方,2-收款方

    @XmlElement(name = "PyeeInf")
    private PyeeInf pyeeInf;//收款方資訊

    @XmlElement(name = "ResfdtInf")
    private ResfdtInf resfdtInf;//備付金資訊

    @XmlElement(name = "TrxInf")
    private TrxInf trxInf;//交易資訊

    @XmlElement(name = "OrdrInf")
    private OrdrInf ordrInf;//訂單資訊

    @XmlElement(name = "BatchId")
    private String batchId;//交易批次號

    @XmlElement(name = "TrxDevcInf")
    private String trxDevcInf;//交易裝置資訊

    //get,set省略……
}

PyerInf.java  ResfdtInf.java  TrxInf.java  OrdrInf.java註解與MsgHeader.java註解一樣

 PyeeInf.java

@XmlRootElement(name = "PyeeInf")
@XmlAccessorType(XmlAccessType.NONE)
public class PyeeInf {

    @XmlElement(name = "PyeeAcctIssrId")
    private String pyeeAcctIssrId;

    @XmlElement(name = "PyeeAcctId")
    private String pyeeAcctId;

    @XmlElement(name = "PyeeAcctNm")
    private String pyeeAcctNm;

    @XmlElement(name = "PyeeAcctTp")
    private List<String> pyeeAcctTp;//有多個同欄位資料

    @XmlElement(name = "PyerTrxTrmTp")
    private String pyeeTrxTrmTp;

    @XmlElement(name = "PyerTrxTrmNo")
    private String pyeeTrxTrmNo;

    //get,set省略……
}

package-info.java  對名稱空間及字首進行處理

@XmlSchema(
        namespace = "urn:iso:std:iso:20022:tech:xsd:pacs.008.001.02",
        elementFormDefault = XmlNsForm.QUALIFIED,
        xmlns = {
                @XmlNs(namespaceURI = "urn:iso:std:iso:20022:tech:xsd:pacs.008.001.02", prefix = "")
        }
)
package com.example.webflux02.domain;

import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

3.xml與物件互相轉換

xml報文轉物件

    /**
     *  解析xml報文,轉化為物件
     * @param string xml報文
     * @return 物件
     */
    @PostMapping(value = "/message", consumes = "application/xml")
    public Root xmlToBean(@RequestBody String string) {
        Root rootInfo=new Root();
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            rootInf=(Root)unmarshaller.unmarshal(new StringReader(string));
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return rootInf;
    }

xml檔案轉物件

    /**
     *  解析xml檔案,轉化為物件
     * @param string 檔案路徑
     * @return
     */
    @PostMapping(value = "/xmlByFile")
    public Root xmlToBeanByFile(@RequestBody String string) {
        Root rootInf=new Root();
        File file=new File(string);
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            rootInf = (Root) unmarshaller.unmarshal(file);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return rootInf;
    }

物件轉xml檔案和xml報文   預設報文頭與要生成的報文頭不相符,因此去掉

    /**
     *  將物件轉化為xml檔案及xml報文
     * @param rootInf
     * @return
     */
    @PostMapping("/beanToXml")
    public String beanToXml(@RequestBody RootInf rootInf) {
        String result = "";
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(RootInf.class);
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);//格式化輸出
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");//編碼格式
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);//去掉預設報文頭
            StringWriter writer = new StringWriter();
            writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");//重寫報文頭
            writer.write("\n");
            marshaller.marshal(rootInf, writer);
            result = writer.toString();
            //寫入到xml檔案中
            BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter(new File("要寫入的xml檔案位置")));
            bufferedWriter.write(result);
            bufferedWriter.close();
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

4.結果

xml轉物件

{
    "msgBody": {
        "pyerInf": {
            "pyerAcctIssrId": "C1010411000013",
            "pyerAcctTp": "00",
            "sgnNo": "130073386132613885",
            "pyerTrxTrmTp": "02",
            "pyerTrxTrmNo": "F93P72HCFR9M"
        },
        "pyerTrxTrmNo": "1",
        "pyeeInf": {
            "pyeeAcctIssrId": "C1010411000013",
            "pyeeAcctId": "282704424720582705",
            "pyeeAcctNm": "[email protected]",
            "pyeeAcctTp": [
                "04",
                "CN",
                "110102"
            ],
            "pyeeTrxTrmTp": "06",
            "pyeeTrxTrmNo": "1D6AP1500"
        },
        "resfdtInf": {
            "instgAcctId": "1001278619005510977",
            "instgAcctNm": "客戶備付金",
            "resfdAcctIssrId": "C1010511003703"
        },
        "trxInf": {
            "trxId": "20170518654321098765432100010205",
            "trxDtTm": "2017-05-19T01:18:23",
            "trxAmt": "CNY175.19",
            "trxCtgy": "0110",
            "bizTp": "100002",
            "acctInTp": "02"
        },
        "ordrInf": {
            "trxId": "20170518100615209112",
            "trxDtTm": "2|2|chd%07515|",
            "trxAmt": "batpay"
        },
        "batchId": "B201705180016",
        "trxDevcInf": "140.205.112.1|F0E1D2C3B4A5||||||"
    },
    "msgHeader": {
        "sndDt": "2017-01-01T14:21:21",
        "msgTp": "epcc.201.001.01",
        "issrId": "31310000001311",
        "drctn": "11",
        "signSn": "313100000013",
        "ncrptnSN": "313100000013",
        "dgtlEnvlp": "asdjjnfsaskjdjgf;lasnlfklsadfosadnfbjhsafnlsdbfsafntrgnidfnjkugfbgdlkgnui"
    }
}

物件轉xml

 <?xml version="1.0" encoding="UTF-8"?>
<root xmlns="urn:iso:std:iso:20022:tech:xsd:pacs.008.001.02">
    <MsgHeader>
        <SndDt>2017-01-01T14:21:21</SndDt>
        <MsgTp>epcc.201.001.01</MsgTp>
        <IssrId>31310000001311</IssrId>
        <Drctn>11</Drctn>
        <SignSN>313100000013</SignSN>
        <NcrptnSN>313100000013</NcrptnSN>
        <DgtlEnvlp>asdjjnfsaskjdjgf;lasnlfklsadfosadnfbjhsafnlsdbfsafntrgnidfnjkugfbgdlkgnui</DgtlEnvlp>
    </MsgHeader>
    <MsgBody>
        <PyerInf>
            <PyerAcctIssrId>C1010411000013</PyerAcctIssrId>
            <PyerAcctTp>00</PyerAcctTp>
            <SgnNo>130073386132613885</SgnNo>
            <PyerTrxTrmTp>02</PyerTrxTrmTp>
            <PyerTrxTrmNo>F93P72HCFR9M</PyerTrxTrmNo>
        </PyerInf>
        <PyerTrxTrmNo>1</PyerTrxTrmNo>
        <PyeeInf>
            <PyeeAcctIssrId>C1010411000013</PyeeAcctIssrId>
            <PyeeAcctId>282704424720582705</PyeeAcctId>
            <PyeeAcctNm>[email protected]</PyeeAcctNm>
            <PyeeAcctTp>04</PyeeAcctTp>
            <PyeeAcctTp>CN</PyeeAcctTp>
            <PyeeAcctTp>110102</PyeeAcctTp>
            <PyerTrxTrmTp>06</PyerTrxTrmTp>
            <PyerTrxTrmNo>1D6AP1500</PyerTrxTrmNo>
        </PyeeInf>
        <ResfdtInf>
            <InstgAcctId>1001278619005510977</InstgAcctId>
            <InstgAcctNm>客戶備付金</InstgAcctNm>
            <ResfdAcctIssrId>C1010511003703</ResfdAcctIssrId>
        </ResfdtInf>
        <TrxInf>
            <TrxId>20170518654321098765432100010205</TrxId>
            <TrxDtTm>2017-05-19T01:18:23</TrxDtTm>
            <TrxAmt>CNY175.19</TrxAmt>
            <TrxCtgy>0110</TrxCtgy>
            <BizTp>100002</BizTp>
            <AcctInTp>02</AcctInTp>
        </TrxInf>
        <OrdrInf>
            <TrxId>20170518100615209112</TrxId>
            <TrxDtTm>2|2|chd%07515|</TrxDtTm>
            <TrxAmt>batpay</TrxAmt>
        </OrdrInf>
        <BatchId>B201705180016</BatchId>
        <TrxDevcInf>140.205.112.1|F0E1D2C3B4A5||||||</TrxDevcInf>
    </MsgBody>
</root>