我正在尝试使用Jaxb从XML对象中提取其中一个对象。它不会返回任何错误日志。但是,它返回一个null对象。请找到代码。请告诉我只有Jaxb(不是用Documentbuilder方式)
<DATAPACKET REQUEST-ID = "4">
<HEADER>
<RESPONSE-TYPE CODE = "0" DESCRIPTION = "Response Error" />
</HEADER>
<BODY>
<ERROR-LIST>
<ERROR-CODE>107</ERROR-CODE>
</ERROR-LIST>
</BODY>
</DATAPACKET>
DataPacket
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "DATAPACKET")
public class DataPacket {
@XmlElement(name ="BODY")
private Body BODY;
public DataPacket (){}
// Setter and getter of Body
}
身体
@XmlAccessorType(XmlAccessType.NONE)
public class Body{
@XmlElement(name ="ERROR-LIST")
private ErrorListDto errorList;
public Body(){}
// Setter and getter of errorList
}
ErrorListDto
@XmlAccessorType(XmlAccessType.NONE)
public class ErrorListDto{
@XmlElement(name="ERROR-CODE")
private List<ErrorCodesDto> errorCodes;
public ErrorListDto(){}
// Setter and getter of errorCodes
}
ErrorCodesDto
@XmlAccessorType(XmlAccessType.NONE)
public class ErrorCodesDto {
@XmlElement(name = "ERROR-CODE")
private String ERROR_CODE;
public ErrorCodesDto() {}
我按如下方式提取值
JAXBContext jc = JAXBContext.newInstance(DataPacket.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StringReader reader = new StringReader(responseXML);
DataPacket dp = (DataPacket) unmarshaller.unmarshal(reader);
Body body = dp.getBODY();
ErrorListDto errorList = body.getErrorList();
System.out.println(errorList.toString()); --> Here it has error code as null
请告诉我这里出了什么问题。任何想法都将不胜感激。
答案 0 :(得分:2)
更改您的ErrorCodesDto
,如下所示:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlValue;
@XmlAccessorType(XmlAccessType.NONE)
public class ErrorCodesDto {
@XmlValue
private String ERROR_CODE;
public ErrorCodesDto() {
}
}
否则你的预期&#34; xml&#34;应包含
<ERROR-LIST>
<ERROR-CODE><ERROR-CODE>107</ERROR-CODE></ERROR-CODE>
</ERROR-LIST>
要回答您的评论,该代码甚至可以使用以下xml
<DATAPACKET REQUEST-ID = "4">
<HEADER>
<RESPONSE-TYPE CODE = "0" DESCRIPTION = "Response Error" />
</HEADER>
<BODY>
<ERROR-LIST>
<ERROR-CODE>107</ERROR-CODE>
<ERROR-CODE>108</ERROR-CODE>
<ERROR-CODE>109</ERROR-CODE>
</ERROR-LIST>
</BODY>
</DATAPACKET>
修改
您也可以在没有ErrorCodesDto
课程的情况下实现这一目标,只需将ErrorListDto
更改为
@XmlElement(name = "ERROR-CODE")
private List<String> errorCodes;