通过Dozer映射XMLGregorianCalendar

时间:2015-02-17 06:08:01

标签: date calendar mapping dozer

我试图映射两个属性,都是XMLGregorianCalendar类型。试图通过推土机实现这一目标,值已被映射,但正在获得如下所示的日期时间值

以XML格式输入

 <urn1:ReservationDate>2015-02-11</urn1:ReservationDate>
 <urn1:ReservationTime>03:28:00</urn1:ReservationTime>

以JSON输出

 "reservationDate": 1423593000000,
  "reservationTime": -7320000

我的推土机映射如下

<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://dozer.sourceforge.net
          http://dozer.sourceforge.net/schema/beanmapping.xsd">
    <configuration>
        <stop-on-errors>true</stop-on-errors>
        <date-format>MM/dd/yyyy HH:mm</date-format>
        <!-- <date-format>MM-dd-yyyy</date-format> -->
        <wildcard>true</wildcard>
        <custom-converters>
        <converter type="com.xxx.util.XMLGC2XMLGC">
        <class-a>javax.xml.datatype.XMLGregorianCalendar</class-a>
        <class-b>javax.xml.datatype.XMLGregorianCalendar</class-b>
        </converter>
        </custom-converters>
    </configuration>

    <mapping>
        <class-a>com.xxx..ReservationType
        </class-a>
        <class-b>com.xxx..ReservationDto
        </class-b>
        <field>
            <a>pnrLocator</a>
            <b>pnrLocator</b>
        </field>
        <field>
            <a>reservationDate</a>
            <b>reservationDate</b>
            <a-hint>java.util.GregorianCalendar</a-hint>
        </field>
    </mapping>
</mappings> 

XMLGC2XMLGC类代码

public class XMLGC2XMLGC extends
DozerConverter<XMLGregorianCalendar, XMLGregorianCalendar> {
    public XMLGC2XMLGC() {
        super(XMLGregorianCalendar.class, XMLGregorianCalendar.class);
    }
    @Override
    public XMLGregorianCalendar convertFrom(XMLGregorianCalendar src,
            XMLGregorianCalendar dest) {
        return src;
    }
    @Override
    public XMLGregorianCalendar convertTo(XMLGregorianCalendar src,
            XMLGregorianCalendar dest) {
        return dest;
    } 

我甚至尝试过Date to XMLGregorianCalendar转换,因为我读了一些文档,说它应该自动发生但我在做同样的事情时会得到这样的异常

java.lang.IllegalAccessException:类org.dozer.util.ReflectionUtils无法使用修饰符访问类org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl的成员\&#34; public \&#34;

请帮忙

1 个答案:

答案 0 :(得分:2)

问题在于JSON序列化。 我必须编写一个自定义序列化器,用于在JSON中正确显示XMLGregorianCalendar日期

代码如下

public class CustomDateSerializer extends JsonSerializer<XMLGregorianCalendar> {    
    @Override
    public void serialize(XMLGregorianCalendar value, JsonGenerator gen, SerializerProvider arg2) throws 
        IOException, JsonProcessingException {      

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = formatter.format(value.toGregorianCalendar().getTime());
        gen.writeString(formattedDate);

    }
}

并注明相应字段如下

@JsonSerialize(using = CustomDateSerializer.class)
    private XMLGregorianCalendar reservationDate;

这足以在JSON中获得正确的日期格式:)

希望这有助于某人!