XStream java.util.Map字段编组

时间:2014-04-02 21:11:59

标签: java xstream

我想在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中某些字段的默认行为,但为其他字段使用自定义转换器。这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:0)

要获取默认行为,请确保UnmarshallingContextAbstractReferenceMarshaller,并致电context.start(object, context)