首页 > 解决方案 > 覆盖第 3 方库类的 XmlAdapter

问题描述

我正在使用 jaxbMarshaller 为第三方库类生成 xml。由于将 Calendar 对象转换为字符串的库 XmlAdapter 未使用 TimeZone 字段,因此编组器为 pojo 类的每个 Calendar 字段生成错误的 xml。

第 3 方库 XmlAdapter 使用以下类进行日历到字符串的转换:

public class DateConversion {
    public static String printDate(Calendar value) {
        if(value != null) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            return format.format(value.getTime());
        }
        return null;
    }
}

所以我想为 Calendar 字段覆盖 XmlAdapter 的行为并尝试下面的示例,但似乎它不起作用:

我的自定义 XmlAdapter 正在使用以下类进行转换:

public class DateConversion {
    public static String printDate(Calendar value, TimeZone timeZone) {
        if(value != null) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            format.setTimeZone(timeZone);
            return format.format(value.getTime());
        }
        return null;
    }
}

然后我完成了注册表,例如:

public @Nullable
    String toPdxmlString(final @NotNull Deals input) {
        try {
            final Marshaller marshaller = jaxbContext.createMarshaller();
            final DateFormatterAdapter dateFormatterAdapter = new DateFormatterAdapter(PdxmlDateTimeUtil.FXONLINE_DEFAULT_DEAL_TIMEZONE);
            marshaller.setAdapter(dateFormatterAdapter);
            StringWriter writer = new StringWriter();
            marshaller.marshal(input, writer);
            return writer.toString();
        } catch (JAXBException exception) {
            LOGGER.error("Unable to marshall the given input Deals: {}, into String using JAXB Context: {}, ... ", input, jaxbContext, exception);
        }
        return null;
    }

谁能帮我知道这是否可行,如果是,我哪里出错了?

标签: javajaxbxmladapter

解决方案


所以我找到了我的解决方案。我扩展了 3rd 方库的 XmlAdapter 并插入了 DateConversion 中的 TimeZone 字段,例如:

public class DateFormatterAdapter extends Adapter2 {
    private final TimeZone timeZone;

    public DateFormatterAdapter(final TimeZone timeZone) {
        this.timeZone = timeZone;
    }

    @Override
    public Calendar unmarshal(String value) {
        return javax.xml.bind.DatatypeConverter.parseDate(value);
    }

    @Override
    public String marshal(Calendar calendar) {
        return DateConversion.printDate(calendar, timeZone);
    }
}

最后将扩展的 XmlAdapter 注册为:

public @Nullable
    String toPdxmlString(final @NotNull Deals input) {
        try {
            final Marshaller marshaller = jaxbContext.createMarshaller();
            final DateFormatterAdapter dateFormatterAdapter = new DateFormatterAdapter(PdxmlDateTimeUtil.FXONLINE_DEFAULT_DEAL_TIMEZONE);
            marshaller.setAdapter(Adapter2.class, dateFormatterAdapter);
            StringWriter writer = new StringWriter();
            marshaller.marshal(input, writer);
            return writer.toString();
        } catch (JAXBException exception) {
            LOGGER.error("Unable to marshall the given input Deals: {}, into String using JAXB Context: {}, ... ", input, jaxbContext, exception);
        }
        return null;
    }

推荐阅读