java - 覆盖第 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;
}
谁能帮我知道这是否可行,如果是,我哪里出错了?
解决方案
所以我找到了我的解决方案。我扩展了 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;
}
推荐阅读
- sql-server - 使用 Python 调用 CURL 的 SQL Server + 代理作业
- excel - 使用带有 MS Edge 的 WScript 下载多个文件会留下打开的 Edge 选项卡
- swift - 从选择器 SwiftUI 中取消选择项目
- python - 交换/转置矩阵列
- javascript - 在对象数组中按一个属性分组并计算另一个属性中的关键字出现次数?
- mysql - MySQL:如何跟踪视图中的更改
- html - Django模板没有加载没有错误
- python - 使用调试工具运行服务器问题
- javascript - 使用语言环境阿拉伯语进行 date.toLocaleDateString 转换在 Chrome 和 firefox 中产生不同的结果
- r - 为具有少量观察的组添加点到 geom_density_ridges