【发布时间】:2014-04-02 21:11:58
【问题描述】:
我想为 xstream 中的对象使用自定义转换器,但默认为某些字段的默认行为。
很遗憾,在TestObject中写map之类的字段时,xstream不会写周围的<map>...</map>标签。
public static class TestObject {
public Map map;
public Object custom;
}
protected static XStream stream = new XStream();
protected static Converter TestObjectConverter = new Converter() {
@Override
public boolean canConvert(Class type) {
return type == TestObject.class;
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
return null;
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
TestObject obj = (TestObject)source;
context.convertAnother(obj.map);
}
};
@Override
protected void runApp() throws Exception {
stream.registerConverter(TestObjectConverter);
TestObject obj = new TestObject();
obj.map = new HashMap();
obj.map.put(1, "asdf");
obj.map.put(2, "qwerty");
String xml = stream.toXML(obj);
return;
};
基本上我希望复制 TestObject 中某些字段的默认行为,但对其他字段使用自定义转换器。最好的方法是什么?
【问题讨论】: