I am trying to unmarshall data from an XML object in Java using SimpleXML. The point of the whole thing was to convert an API from JAXB to SimpleXML. Therefore, I used the annotation way of parsing the document. Here is some code:
In the User class:
@Element(name="created", required=false)
private Date created;
The programmer who wrote the API used a DateAdapter to turn the String pulled in from the XML directly into a date. I attempted to convert it to SimpleXML. My assumption is that a Transformer used the same approach. Here is that code before and after...
Before:
public class DateAdapter extends XmlAdapter<String, Date> {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public Date unmarshal(String date) throws Exception {
return df.parse(date);
}
public String marshal(Date date) throws Exception {
return df.format(date);
}
}
After:
public class DateAdapter implements Transform<Date> {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public Date read(String date) throws Exception {
return df.parse(date);
}
@Override
public String write(Date date) throws Exception {
return df.format(date);
}
}
I assume I did the conversion wrong because I am now getting Unparsable date errors. The weird part is that, even if I put if-else or try-catch blocks within the read and write methods I still get the error.
So I think the main question is, how do I properly write an adapter like the JAXB one to marshall/unmarshall between the String from the XML and a Date object.