2013-08-05 28 views
1

我有以下XML結構:反序列化回調

<key> 
    <element> 
     someValue 
    </element> 

    <!-- lots of other elements which should be deserialized into the class --> 

    <other> 
     someOtherValue 
    </other> 
</key> 

我用Simple將其反序列化到下面的Java類:

@Root(name = "key", strict = false) 
public class Key { 

    @Element(name = "element") 
    private String element; 

    // lots of more fields should be deserialized from xml 
} 

注意,類不有一個other元素的字段。我不需要課堂上的價值,但在其他地方。我如何攔截解析並提取此other元素的值?

回答

0

您可以通過多種方式實現,但最好是使用ConverterStrategy。轉換器是兩者中最簡單的。

+0

謝謝!我的不好,也許OP是誤導性的。我編輯它。我的問題是'Key'類有很多字段,我想對這些字段使用默認的反序列化,並以自定義的方式提取額外的元素。這可能嗎? – WonderCsabo

+0

你有更多的提示嗎? :( – WonderCsabo

0

我認爲Strategy方法不起作用,因爲他們使用帶註釋的類作爲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; 
    } 

}

放在一起:

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()); 

這不是太優雅,但可能適合您的需要。

+0

謝謝!我的OP有點誤導。:(這只是一個簡化的例子,實際上'Key'類包含很多其他字段。是否有任何方法可以在類字段上調用默認轉換器,使用這個額外的元素?我編輯到OP。 – WonderCsabo

+0

@WonderCsabo您是否有可能改變XML模式?例如,將'other'的值放在元素'key'的屬性中 – Katona

+0

不幸的是。 xml來自一個不可修改的接口,如果我們改變它,其他舊的代碼會破壞。:(是的,我知道這個模式設計不好。 – WonderCsabo

0

我不能讓一個StragegyConverter的解決方案爲納克卡託納建議。不過,我提出了一個解決方法,該方法可行,但並不太好。

/* 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作爲靜態類型,所以我簡單地忘記另一個字段是在該對象。當我堅持我的數據時,我也堅持爲Key,所以mOtherValue不再與班級相連。正如你所看到的SerializedKey類是包私有的,所以我不公開這個幫助類到我的應用程序的任何其他組件。