我正在使用jaxbMarshaller为第三方库类生成xml。由于将日历对象转换为字符串的XmlAdapter库未使用TimeZone字段,因此marshaller为pojo类的每个Calendar字段生成了错误的xml。
3rd Party库XmlAdapter正在将下面的类用于Calendar到字符串的转换:
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;
}
}
所以我想覆盖XmlAdapter的Calendar字段的行为,并尝试下面的示例,但似乎不起作用:
我的自定义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;
}
谁能帮我知道这是否可行,如果可以,我哪里做错了?
最佳答案
所以我找到了解决方案。我扩展了第三方库的XmlAdapter,并在Data Conversion中插入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;
}