使用 xstream 的自定义转换器
我的类范围需要一个自定义转换器:
class Scope {
private final String name;
private final SomeProp prop;
private final Item[] items;
//...
}
我为 SomeProp 注册了我的转换器。但我想使用 Item (和所有子类)的默认转换器。
我怎样才能做到呢?
我尝试覆盖 marshal/unmarshal:
public void marshal(Object val, HierarchicalStreamWriter writer,
MarshallingContext context) {
//... saving name and prop
writer.startNode("items");
ArrayConverter conv = new ArrayConverter(mapper);
assert(conv.canConvert(items.members.getClass()));
conv.marshal(items.members, writer, context);
writer.endNode);
}
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
//... reading name and prop
reader.moveDown();
assert("items".equals(reader.getNodeName()));
ArrayConverter conv = new ArrayConverter(mapper);
Item[] items = (Item[])conv.unmarshal(reader, context);
//...
}
但由于某种原因 unmarshal 不起作用。
I need a custom convertor for my class Scope:
class Scope {
private final String name;
private final SomeProp prop;
private final Item[] items;
//...
}
I registered my converter for SomeProp. But I want to use default converter for Item (and all sub-classes).
How I can do it?
I tried to override marshal/unmarshal:
public void marshal(Object val, HierarchicalStreamWriter writer,
MarshallingContext context) {
//... saving name and prop
writer.startNode("items");
ArrayConverter conv = new ArrayConverter(mapper);
assert(conv.canConvert(items.members.getClass()));
conv.marshal(items.members, writer, context);
writer.endNode);
}
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
//... reading name and prop
reader.moveDown();
assert("items".equals(reader.getNodeName()));
ArrayConverter conv = new ArrayConverter(mapper);
Item[] items = (Item[])conv.unmarshal(reader, context);
//...
}
but by some reason unmarshal is not working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的描述不是很清楚,但我认为您正在尝试做比需要的更多的工作。如果您想要 SomeProp 的自定义转换器以及其他所有内容的默认转换器,您所要做的就是
如果我在您的问题中遗漏了某些内容,请澄清。
Your description isn't very clear, but I think you're trying to do far more work than is needed. If you want a custom converter for SomeProp and default for everything else, all you have to do is
If I missed something in your question, please clarify.
我阅读了 ArrayConverter 和 AbstractCollectionConverter 的源代码并重写了 unmarshal,如下所示:
但在循环引用的情况下出现错误。
因此,最好的方法是瑞安·斯图尔特 (Ryan Stewart) 提出的。
I read source code for ArrayConverter and AbstractCollectionConverter and rewrote unmarshal as follow:
But I got an error in case of cyclic references.
So the best way was sudgested by Ryan Stewart.