如何为某个元素附加XStream转换器?

时间:2023-01-14 07:58:27

It is easy to set a converter for a certain type (http://x-stream.github.io/javadoc/com/thoughtworks/xstream/XStream.html gives an example):

为某种类型设置转换器很容易(http://x-stream.github.io/javadoc/com/thoughtworks/xstream/XStream.html给出一个例子):

xstream.registerConverter(new SqlTimestampConverter());
xstream.registerConverter(new DynamicProxyConverter());

I would like to register a converter, but on different element names. The Converter interface does not offer the name of the element.

我想注册一个转换器,但在不同的元素名称。 Converter接口不提供元素的名称。

For example: A date should be converted to a detailed string if the element name (property name) will be in <longDate> but short if in <shortDate>. How can I add different converters based on the property name? Something like xstream.registerConverter( Class classtype, propertyname, converter ) didn't exist but would be nice.

例如:如果元素名称(属性名称)将在 中,则日期应转换为详细字符串,如果在 中则为short。如何根据属性名称添加不同的转换器?类似xstream.registerConverter(类classtype,propertyname,converter)之类的东西不存在,但会很好。

I know that I can use a specialised version of a PrettyPrintWriter but that seems to much work for this simple job. Any other ideas?

我知道我可以使用PrettyPrintWriter的专用版本,但这对于这个简单的工作似乎很有用。还有其他想法吗?

BTW: I could use an annotation @XStreamConverter(XXX.class) but I don't want to use annotations. I want my bean free of any annotation.

BTW:我可以使用注释@XStreamConverter(XXX.class),但我不想使用注释。我希望我的bean没有任何注释。

1 个解决方案

#1


6  

Use registerLocalConverter() instead of registerConverter().

使用registerLocalConverter()而不是registerConverter()。

xstream.registerLocalConverter( MyClazz.class, "property", new MyConverter() );

#1


6  

Use registerLocalConverter() instead of registerConverter().

使用registerLocalConverter()而不是registerConverter()。

xstream.registerLocalConverter( MyClazz.class, "property", new MyConverter() );