program tip

JAXB가 xsd : dateTime을 마샬링 할 때 사용되는 날짜 형식을 어떻게 지정합니까?

radiobox 2020. 9. 25. 07:45
반응형

JAXB가 xsd : dateTime을 마샬링 할 때 사용되는 날짜 형식을 어떻게 지정합니까?


JAXB가 날짜 객체 ( XMLGregorianCalendar)를 xsd : dateTime 요소로 마샬링 할 때 결과 XML의 형식을 어떻게 지정할 수 있습니까?

예 : 기본 데이터 형식은 밀리 초 <StartDate>2012-08-21T13:21:58.000Z</StartDate>를 생략하는 데 필요한 밀리 초를 사용합니다.<StartDate>2012-08-21T13:21:58Z</StartDate>

사용할 출력 양식 / 날짜 형식을 어떻게 지정할 수 있습니까? 개체 javax.xml.datatype.DatatypeFactory를 만드는 데 사용 하고 있습니다 XMLGregorianCalendar.

XMLGregorianCalendar xmlCal = datatypeFactory.newXMLGregorianCalendar(cal);

를 사용하여 XmlAdapter날짜 유형이 XML에 기록되는 방식을 사용자 지정할 수 있습니다 .

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class DateAdapter extends XmlAdapter<String, Date> {

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

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

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

}

그런 다음 @XmlJavaTypeAdapter주석을 XmlAdapter사용하여를 특정 필드 / 속성에 사용해야 함 을 지정합니다 .

@XmlElement(name = "timestamp", required = true) 
@XmlJavaTypeAdapter(DateAdapter.class)
protected Date timestamp; 

xjb 바인딩 파일 사용 :

<jxb:javaType name="java.time.ZonedDateTime" 
              xmlType="xs:dateTime"

    parseMethod="my.package.DateAdapter.parseDateTime"
    printMethod="my.package.DateAdapter.formatDateTime" />

위에서 언급 한 주석을 생성합니다.


이 예제와 같이 SimpleDateFormat을 사용하여 XMLGregorianCalendar를 만듭니다.

public static XMLGregorianCalendar getXmlDate(Date date) throws DatatypeConfigurationException {
    return DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd").format(date));
}

public static XMLGregorianCalendar getXmlDateTime(Date date) throws DatatypeConfigurationException {
    return DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(date));
}

The first method creates an instance of XMLGregorianCalendar that is formatted by the XML marshaller as a valid xsd:date, the second method results in a valid xsd:dateTime.


Very easy way to me. Formatting XMLGregorianCalendar for marshalling in java.

I just create my data in the good format. The toString will be called producing the good result.

public static final XMLGregorianCalendar getDate(Date d) {
    try {
        return DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd").format(d));
    } catch (DatatypeConfigurationException e) {
        return null;
    }
}

https://www.baeldung.com/jaxb

public class DateAdapter extends XmlAdapter<String, Date> {

    private static final ThreadLocal<DateFormat> dateFormat 
      = new ThreadLocal<DateFormat>() {

        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    }

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

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

Usage:

import com.company.LocalDateAdapter.yyyyMMdd;
...

@XmlElement(name = "PROC-DATE")
@XmlJavaTypeAdapter(yyyyMMdd.class)
private LocalDate processingDate;

LocalDateAdapter

import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class LocalDateAdapter extends XmlAdapter<String, LocalDate> {

    public static final class yyyyMMdd extends LocalDateAdapter {
        public yyyyMMdd() {
            super("yyyyMMdd");
        }
    }

    public static final class yyyy_MM_dd extends LocalDateAdapter {
        public yyyy_MM_dd() {
            super("yyyy-MM-dd");
        }
    }

    private final DateTimeFormatter formatter;

    public LocalDateAdapter(String pattern) {
        formatter = DateTimeFormat.forPattern(pattern);
    }

    @Override
    public String marshal(LocalDate date) throws Exception {
        return formatter.print(date);
    }

    @Override
    public LocalDate unmarshal(String date) throws Exception {
        return formatter.parseLocalDate(date);
    }
}

참고URL : https://stackoverflow.com/questions/13568543/how-do-you-specify-the-date-format-used-when-jaxb-marshals-xsddatetime

반응형