0

我正在使用 spring 运行一个 webapp,并且我使用 xstream 作为我的序列化工具。我已经定义了一个包含自定义转换器的 marsheller,但是在读取 xml 时,我注册的转换器似乎被忽略了,因为 xstream 无法正确解析某些字段。

这是编组器的init函数:

public void init() {
    XStream xstream = new XStream() {

        protected MapperWrapper wrapMapper(MapperWrapper next) {
            return new MapperWrapper(next) {

                public boolean shouldSerializeMember(Class definedIn, String fieldName) {
                    return definedIn != Object.class ? super.shouldSerializeMember(definedIn, fieldName) : false;
                }

            };
        }

    };
    xstream.setMode(XStream.NO_REFERENCES);
    xstream.addDefaultImplementation(ArrayList.class, PersistentList.class);
    xstream.addDefaultImplementation(ArrayList.class, PersistentBag.class);
    xstream.addDefaultImplementation(HashMap.class, PersistentMap.class); 
    xstream.addDefaultImplementation(java.util.HashSet.class, PersistentSet.class);

    xstream.alias("Array", PersistentBag.class);
    xstream.alias("list", PersistentBag.class);

    Mapper mapper = xstream.getMapper();
    xstream.registerConverter(new HibernateCollectionConverter(mapper));
    xstream.registerConverter(new HibernateMapConverter(mapper));
    xstream.registerConverter(new DateConverter());
    xstream.registerConverter(new TimeStampCustomConverter());
    xstream.registerConverter(new LongConverter());
    xstream.registerConverter(new IntConverter());
    xstream.registerConverter(new DoubleConverter());

}

我错过了什么?

4

1 回答 1

1

您在类的特定实例上注册转换器等XStream,因此您需要保存对配置的引用,而XStream不是init()方法的局部变量。或者,使其成为一个返回的方法,XStream然后在需要编组器时调用它:

protected XStream createXStream() {
  XStream xs = new XStream();
  // ...
  xs.registerConverter(...);
  return xs;
}
于 2012-12-28T21:10:02.613 回答