Xstream的jodatime本地日期显示 [英] Xstream's jodatime Local Date display

查看:71
本文介绍了Xstream的jodatime本地日期显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用xstrem将jodatime本地日期序列化为xml. 但是,当输出生成的xml时,LocalDate的格式不容易阅读. 见下文:

I'm using xstrem to serialise a jodatime local date into xml. However when output the generated xml the LocalDate is not in an easily readable format. See below:

<date>
    <iLocalMillis>1316563200000</iLocalMillis>
    <iChronology class="org.joda.time.chrono.ISOChronology" reference="../../tradeDate/iChronology"/>

有什么想法可以让xstream以一种不会吸引我的格式显示日期吗?

Any ideas how I can get xstream to display the date in a format that won't drive me up the wall?

推荐答案

这是我成功使用的内容.我相信我在第一篇文章中提到的链接上使用了信息.

Here's what I have used successfully. I believe I used the info at the link mentioned in the first post.

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);
            }
    }

}

您可以按以下方式注册:

You can register it like:

XStream xstream = new XStream(new StaxDriver());
xstream.registerConverter(new JodaTimeConverter());

这篇关于Xstream的jodatime本地日期显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆