5

i have a simple xml string like this

<table>
   <test_id>t59</test_id>
   <dateprix>2013-06-06 21:51:42.252</dateprix>   
   <nomtest>NOMTEST</nomtest>
   <prixtest>12.70</prixtest>
   <webposted>N</webposted>
   <posteddate>2013-06-06 21:51:42.252</posteddate>
</table>

I have pojo class for this xml string like this

@XmlRootElement(name="test")
public class Test {
    @XmlElement
    public String test_id;
    @XmlElement
    public Date dateprix;
    @XmlElement
    public String nomtest;
    @XmlElement
    public double prixtest;
    @XmlElement
    public char webposted;
    @XmlElement
    public Date posteddate;
}

I am using jaxb for xml binding to java object. code is

try {
    Test t = new Test
    JAXBContext jaxbContext = JAXBContext.newInstance(t.getClass());
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    t = (Test) jaxbUnmarshaller.unmarshal(new InputSource(new StringReader(xml))); // xml variable contain the xml string define above
} catch (JAXBException e) {
    e.printStackTrace();
}

Now my issue is that after binding with the java object i got null for date variable (dateprix and posteddata) so how could i get value for this.

If I use "2013-06-06" i got the data object but for "2013-06-06 21:51:42.252" i got null.

Waqas Ali
  • 1,642
  • 4
  • 32
  • 55
  • 1
    Check http://stackoverflow.com/questions/5775860/mapping-java-date-object-to-xml-schema-datetime-format for the correct date format. – SJuan76 Jun 11 '13 at 16:37

1 Answers1

6

JAXB expects date in XML in xsd:date (yyyy-MM-dd) or xsd:dateTime format (yyyy-MM-ddTHH:mm:ss.sss). 2013-06-06 21:51:42.252 is not a valid dateTime format 'T' (date/time separator) is missing. You need a custom XmlAdapter to make JAXB convert it to a Java Date. Eg

class DateAdapter extends XmlAdapter<String, Date> {
    DateFormat f = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS");

    @Override
    public Date unmarshal(String v) throws Exception {
        return f.parse(v);
    }

    @Override
    public String marshal(Date v) throws Exception {
        return f.format(v);
    }
}

class Type {
    @XmlJavaTypeAdapter(DateAdapter.class)
    public Date dateprix;
...
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275