1.引入maven 依赖包
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.41</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
</dependency>
2.改造vo:
2.1 凭证xml格式如下:
<RESPONSE>
<COMPANYCODE>1100</COMPANYCODE>
<VOUCHER>
<COMPANYNUMBER>1100</COMPANYNUMBER>
<BOOKEDDATE>2024-08-21</BOOKEDDATE>
......其他属性省略
</VOUCHER>
<VOUCHER>
<COMPANYNUMBER>1100</COMPANYNUMBER>
<BOOKEDDATE>2024-08-21</BOOKEDDATE>
......其他属性省略
</VOUCHER>
<RESPONSE>
2.2 对应xml转Java对象格式:
2.2.1: 根( <RESPONSE>)对象:
import lombok.Data;
import javax.xml.bind.annotation.*;
import java.util.List;
@Data
@XmlRootElement(name="RESPONSE")
@XmlAccessorType(XmlAccessType.FIELD)
public class WSWSVoucherList {
@XmlElement(name="COMPANYCODE")
private String COMPANYCODE;
@XmlElement(name="VOUCHER")
private List<WSWSVoucher> VOUCHERS;
}
2.2.2 :</VOUCHER>对象对应实体类:
import lombok.Data;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class WSWSVoucher extends WSBean implements java.io.Serializable {
@XmlElement(name ="CASHASSTACTTYPE5")
private java.lang.String cashAsstActType5 ;
@XmlElement(name ="OPPACCOUNTSEQ")
private int oppAccountSeq ;
@XmlElement(name ="CASHASSTACTTYPE4")
private java.lang.String cashAsstActType4 ;
........其他对应属性与xml里对应字段一致,此处省略。按需增加
}
3.将xml转换成对应的实体类:
try {
File file = new File("E:\\凭证.xml");//红色为对应xml的位置和名称
JAXBContext jaxbContext = JAXBContext.newInstance(WSWSVoucherList.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(str);
// Object o=jaxbUnmarshaller.unmarshal(file);
WSWSVoucherList data1 = (WSWSVoucherList) jaxbUnmarshaller.unmarshal(file);
System.out.println(data1);
System.out.println(JSON.toJSONString(data1));
// Now you can access the data in the 'data' object.
} catch (Exception e) {
e.printStackTrace();
}