Bind XML Date to Java Object Date

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 a pojo class for this xml string such as

 @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 to bind xml to a java object. code

 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 problem is that after binding to the java object, I got null for the date variable (dateprix and publisheddata), since I can get the value for this.

If I use "2013-06-06", I got a data object, but for "2013-06-06 21: 51: 42.252" I have zero.

+4
source share
1 answer

JAXB expects a date in XML in the format xsd: date (yyyy-MM-dd) or xsd: dateTime (yyyy-MM-ddTHH: mm: ss.sss). 2013-06-06 21: 51: 42.252 Invalid date format DateTime 'T' (date / time separator) missing. You need a custom XmlAdapter for JAXB to convert it to Java Date. For instance,

 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; ... 
+4
source

Source: https://habr.com/ru/post/1485649/


All Articles