JAXB, Custom bindings, Adapter1.class and Joda-time

前端 未结 7 1613
时光说笑
时光说笑 2021-01-11 15:38

I have a problem with the way JAXB is generating the bound classes for an XML schema (which, for sake of precision, I cannot modify). I want to map a xsd:date type to a Joda

相关标签:
7条回答
  • 2021-01-11 16:03

    I found this solution as useful http://blog.bdoughan.com/2011/05/jaxb-and-joda-time-dates-and-times.html

    You will create an adapter

    package blog.jodatime;
    
    import javax.xml.bind.annotation.adapters.XmlAdapter;
    import org.joda.time.DateTime;
    
    public class DateTimeAdapter 
        extends XmlAdapter<String, DateTime>{
    
        public DateTime unmarshal(String v) throws Exception {
            //return new DateTime(v); - old solution that didn't properly handled the timezone
            return DateTime.parse(v);
        }
    
        public String marshal(DateTime v) throws Exception {
            return v.toString();
        }
    
    }
    

    Then register it with annotations by defining a blog/jodatime/package-info.java in your sources

    @XmlJavaTypeAdapters({ @XmlJavaTypeAdapter(type = DateTime.class, value = JodaDateTimeJaxbAdapter.class) })
    package blog.jodatime;
    
    import javax.xml.bind.annotation.adapters.*;
    
    import org.joda.time.*;
    

    Then you should expect that the serialization of DateTime is done without any other changes, just don't forget to annotate your class with @XmlRootElement.

    0 讨论(0)
提交回复
热议问题