我希望将一些XML树类分解为文本节点,但无法在我的用例中起作用:抽象类层次结构。
我尝试以编程方式注册转换器,以在具体类上对其进行声明(API文档甚至说已处理继承的字段)。
@Bean
public Marshaller marshaller() {
XStreamMarshaller marshaller = new XStreamMarshaller();
marshaller.setAutodetectAnnotations(true);
return marshaller;
}
@XStreamConverter(value = ToAttributedValueConverter.class, strings = "value")
public abstract class AbstractProp {
@XStreamAsAttribute
private final String name;
private final String value;
}
@XStreamAlias("boolProp")
public class BoolProp extends AbstractProp {
public BoolProp(String name, Boolean value) {
super(name, value.toString());
}
}
预期
实际
答案 0 :(得分:0)
好的。我在源代码中发现继承有什么问题:
public class ToAttributedValueConverter implements Converter {
...
@Override
public boolean canConvert(final Class<?> type) {
return this.type == type;
}
所以我将其作为解决方法:
public class TextNodeConverter extends ToAttributedValueConverter {
private final Class<?> type;
public TextNodeConverter(Class type, Mapper mapper, ReflectionProvider reflectionProvider, ConverterLookup lookup) {
this(type, mapper, reflectionProvider, lookup, null, null);
}
public TextNodeConverter(Class type, Mapper mapper, ReflectionProvider reflectionProvider, ConverterLookup lookup,
String valueFieldName) {
this(type, mapper, reflectionProvider, lookup, valueFieldName, null);
}
public TextNodeConverter(Class type, Mapper mapper, ReflectionProvider reflectionProvider, ConverterLookup lookup,
String valueFieldName, Class valueDefinedIn) {
super(type, mapper, reflectionProvider, lookup, valueFieldName, valueDefinedIn);
this.type = type;
}
@Override
public boolean canConvert(final Class type) {
return this.type.isAssignableFrom(type);
}
}
好吧,...换向转换器后,它就像一个魅力:-)