使用JAXB将Java对象转换为XML时遇到以下异常。 跟随是代码和例外。
public class JMSExample {
private static String jaxbObjectToXML(Message message)
{
String xmlContent="";
try
{
//Create JAXB Context
JAXBContext jaxbContext = JAXBContext.newInstance(Message.class);
//Create Marshaller
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//Required formatting??
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//Print XML String to Console
StringWriter sw = new StringWriter();
//Write XML to StringWriter
jaxbMarshaller.marshal(message, sw);
//Verify XML Content
xmlContent = sw.toString();
System.out.println( xmlContent );
} catch (JAXBException e) {
e.printStackTrace();
}
return xmlContent;
}
public static void main(String[] args) throws JMSException {
Event event=new Event();
event.setEntity("emirates");
event.setTaskId(null);
event.setPeriodEndDate(new Date(20190531));
event.setTaskDate("01-Jun-2019");
event.setFrequency("Month End");
event.setClientId(6029);
event.setFundId(44949);
event.setReportName("trial");
event.setReportUpdatedAt("12-Jun-2019 07:46:25");
Message employee=new Message();
List <Event> enityList=new ArrayList<Event>();
enityList.add(event);
employee.setEvent(enityList);
//Method which uses JAXB to convert object to XML
String t=jaxbObjectToXML(employee);
}}
消息类别:
@XmlRootElement(name = "Message")
@XmlAccessorType(XmlAccessType.FIELD) 公共类消息{
@XmlPath("Event")
private List <Event> Event = new ArrayList<Event>();
public List<Event> getEvent() {
return Event;
}
public void setEvent(List<Event> event) {
this.Event = event;
};
}
事件类:
@XmlAccessorType(XmlAccessType.FIELD)
public class Event {
@XmlAttribute (name="Entity")
private String Entity;
private String TaskId;
private Date PeriodEndDate;
private String TaskDate;
private String Frequency;
private int ClientId;
private int FundId;
private String ReportName;
private String ReportUpdatedAt;
public void setEntity(String Entity) {
this.Entity = Entity;
}
public void setTaskId(String taskId) {
this.TaskId = taskId;
}
public void setPeriodEndDate(Date periodEndDate) {
PeriodEndDate = periodEndDate;
}
public void setTaskDate(String taskDate) {
this.TaskDate = taskDate;
}
public void setFrequency(String frequency) {
this.Frequency = frequency;
}
public void setClientId(int clientId) {
this.ClientId = clientId;
}
public void setFundId(int fundId) {
this.FundId = fundId;
}
public void setReportName(String reportName) {
this.ReportName = reportName;
}
public void setReportUpdatedAt(String reportUpdatedAt) {
this.ReportUpdatedAt = reportUpdatedAt;
}
}
面临的异常: [Exception [EclipseLink-25007](Eclipse Persistence Services-2.5.0.v20130507-3faac2b):org.eclipse.persistence.exceptions.XMLMarshalException 异常描述:在项目中找不到类com.trial.test.message.Message的描述符。对于JAXB,如果使用TypeMappingInfo []引导了JAXBContext,则必须调用一个接受TypeMappingInfo作为输入参数的编组方法。]