我正在使用 xstrem 将 jodatime 本地日期序列化为 xml。
然而,当输出生成的 xml 时,LocalDate 的格式并不易于阅读。
见下文:
<date>
<iLocalMillis>1316563200000</iLocalMillis>
<iChronology class="org.joda.time.chrono.ISOChronology" reference="../../tradeDate/iChronology"/>
有什么想法可以让 xstream 以不会让我烦恼的格式显示日期吗?
这是我已经成功使用的。我相信我使用了第一篇文章中提到的链接中的信息。
import java.lang.reflect.Constructor;
import org.joda.time.DateTime;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
public final class JodaTimeConverter implements Converter {
@Override
@SuppressWarnings("unchecked")
public boolean canConvert(final Class type) {
return (type != null) && DateTime.class.getPackage().equals(type.getPackage());
}
@Override
public void marshal(final Object source, final HierarchicalStreamWriter writer,
final MarshallingContext context) {
writer.setValue(source.toString());
}
@Override
@SuppressWarnings("unchecked")
public Object unmarshal(final HierarchicalStreamReader reader,
final UnmarshallingContext context) {
try {
final Class requiredType = context.getRequiredType();
final Constructor constructor = requiredType.getConstructor(Object.class);
return constructor.newInstance(reader.getValue());
} catch (final Exception e) {
throw new RuntimeException(String.format(
"Exception while deserializing a Joda Time object: %s", context.getRequiredType().getSimpleName()), e);
}
}
}
你可以这样注册:
XStream xstream = new XStream(new StaxDriver());
xstream.registerConverter(new JodaTimeConverter());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)