Java 反序列化非字段元素的回调
我有以下XML结构:Java 反序列化非字段元素的回调,java,xml,xml-serialization,simple-framework,Java,Xml,Xml Serialization,Simple Framework,我有以下XML结构: <key> <element> someValue </element> <!-- lots of other elements which should be deserialized into the class --> <other> someOtherValue </other> </key> 请注意,该类没有用于其他元素的
<key>
<element>
someValue
</element>
<!-- lots of other elements which should be deserialized into the class -->
<other>
someOtherValue
</other>
</key>
请注意,该类没有用于
其他
元素的字段。我不需要它在课堂上的价值,但在另一个地方。如何截取解析并提取此其他元素的值?您可以通过多种方法来完成,最好使用a或a。转换器是这两种方法中最简单的。我认为策略
方法不起作用,因为它们使用带注释的类作为XML模式,而模式中不存在的内容将不会被处理(访问者不能访问)
转换器可按如下方式使用:
@Root(name = "key", strict = false)
@Convert(KeyConverter.class)
public class Key {
private String element;
public Key(String elementValue) {
element = elementValue;
}
}
转换器在转换期间存储值:
public class KeyConverter implements Converter<Key> {
private String otherValue;
@Override
public Key read(InputNode node) throws Exception {
String elementValue = node.getNext("element").getValue().trim();
otherValue = node.getNext("other").getValue().trim();
return new Key(elementValue);
}
@Override
public void write(OutputNode arg0, Key arg1) throws Exception {
throw new UnsupportedOperationException();
}
/**
* @return the otherValue
*/
public String getOtherValue() {
return otherValue;
}
这不太优雅,但可能适合您的需要。我无法用策略或转换器来解决问题,正如ng和Katona所建议的那样。然而,我做了一个变通方法,虽然有效,但不太好
/* package */ class SerializedKey extends Key {
@Element(name = "other", required = false)
private int mOtherValue;
public int getOtherValue() {
return mOtherValue;
}
}
...
Serializer serializer = new Persister();
SerializedKey key = serializer.read(SerializedKey.class, mInputStream);
int otherValue = key.getOtherValue();
在序列化包之外,我使用Key
作为静态类型,因此我忘记了该对象中还有另一个字段。当我持久化我的数据时,我也会持久化为键
,因此母值
不再连接到类。如您所见,SerializedKey
类是包私有的,因此我不会将此帮助程序类公开给我的应用程序的任何其他组件。谢谢!我的评论有点误导(这只是一个简化的示例,实际上,键
类包含许多其他字段。是否有任何方法可以调用类字段上的默认转换器,并在额外元素上使用它?我编辑为OP.@WonderCsabo您是否有可能更改XML模式?例如,将其他
的值放入元素key
的一个属性不幸不是。xml来自一个不可修改的接口,如果我们更改它,其他旧代码就会中断:(是的,我知道这个模式设计得不好。谢谢!我的不好,可能是OP误导了我。我编辑了它。我的问题是Key
类有很多字段,我想对这些字段使用默认反序列化,并以自定义方式提取额外的元素。这可能吗?你还有其他提示吗?:(
Registry registry = new Registry();
KeyConverter keyConverter = new KeyConverter();
registry.bind(Key.class, keyConverter);
Persister serializer = new Persister(new RegistryStrategy(registry));
Key key = serializer.read(Key.class, this.getClass().getResourceAsStream("key.xml"));
// Returns the value "acquired" during the last conversion
System.out.println(keyConverter.getOtherValue());
/* package */ class SerializedKey extends Key {
@Element(name = "other", required = false)
private int mOtherValue;
public int getOtherValue() {
return mOtherValue;
}
}
...
Serializer serializer = new Persister();
SerializedKey key = serializer.read(SerializedKey.class, mInputStream);
int otherValue = key.getOtherValue();