Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind joda-time with jaxb

I am having a class like this

@XmlRootElement(name = "executionStats")
public class ScriptExecutionStatistics {

private DateTime start;
private DateTime end;

public ScriptExecutionStatistics() { }

public ScriptExecutionStatistics(DateTime start, DateTime end) {
    this.start = start;
    this.end = end;
}

@XmlAttribute
public DateTime getStart() {
    return start;
}

public void setStart(DateTime start) {
    this.start = start;
}

@XmlAttribute
public DateTime getEnd() {
    return end;
}

public void setEnd(DateTime end) {
    this.end = end;
}

}

and I would like to serialize it in xml, so it would look like this

<scriptExecutionStatistics start="17.08.2015 18:17:00" end="17.08.2015 18:18:00" />

I know that an adapter would be necessary if I want to bind joda time with jaxb, but it is confusing I am not getting it really. so I have started with

public class DateTimeAdapter extends XmlAdapter<ScriptExecutionStatistics, DateTime>{
private static DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

@Override
public DateTime unmarshal(ScriptExecutionStatistics vt) throws Exception {
    throw new UnsupportedOperationException("Not supported yet.");
}

@Override
public ScriptExecutionStatistics marshal(DateTime bt) throws Exception {
    ScriptExecutionStatistics stats = new ScriptExecutionStatistics();

}

}

Could you please help me to get it done. Thanks in advance

like image 231
amsalk Avatar asked Oct 19 '25 16:10

amsalk


1 Answers

DateTimeAdapter should marshal/unmarshal DateTime to/from Stringe.g.

public class DateTimeAdapter extends XmlAdapter<String, DateTime>{
   private static DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

   @Override
   public DateTime unmarshal(String vt) throws Exception {
       return dtf.parseDateTime(vt);
   }

   @Override
   public String marshal(DateTime bt) throws Exception {
       return dtf.print(bt);

   }
}

Also you should annotate appropriate fields/getters in ScriptExecutionStatistics with @XmlJavaTypeAdapter annotation

@XmlJavaTypeAdapter(DateTimeAdapter.class)
@XmlAttribute
public DateTime getStart() {
    return start;
}
like image 198
Ilya Avatar answered Oct 21 '25 07:10

Ilya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!