tags:

views:

27

answers:

1

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.

A: 

I fixed the problem. It had nothing to do with the API I was working on itself, but rather the conversion of a double to a date when unmarshalled by the actually XML framework. The double stored in the XML was in Epoch time in seconds, with decimals for milliseconds. SimpleXML could not seem to handle the decimals properly. My workaround was to just ask for a double instead of having the data be unmarshalled into a Date. So I got rid of the whole adapter and just changed

@Element(name="created", required=false)
private Date created;

to

@Element(name="created", required=false)
private double created;

I'm sure that there is a way with Simple to convert this into a Date after the fact, but I figure it's better to just leave it as is.

AndrewKS