使用XStream將XML轉化成對象,忽略沒有關聯的屬性 轉

使用背景: 
在和第三方系統集成的時候,數據傳輸的格式都是XML,第三方獲取到數據之後,轉化成XML發送過來,我方系統根據XML轉化成對象,如果第三方系統的數據類型增加一個字段,再傳輸過來時,一般會拋出 
“no such field”類似於這樣的錯誤。

問題分析 
我們在使用XStream對象時,一般都會直接new一個對象出來,例如

XStream xstream = new XStream();

這樣使用之後,xml中的所有屬性都需要被待轉化的模型識別,假如有一個字段沒有對應上,即會拋出錯誤。 
問題解決方案 
XStream 官方也提供這樣一種構造方法。

// Initialize XStream as shown below to ignore fields that are not defined in your bean.
XStream xstream = new XStream() {
    @Override
    protected MapperWrapper wrapMapper(MapperWrapper next) {
        return new MapperWrapper(next) {
            @Override
            public boolean shouldSerializeMember(Class definedIn, String fieldName) {
                if (definedIn == Object.class) {
                    return false;
                }
                return super.shouldSerializeMember(definedIn, fieldName);
            }
        };
    }
};
xstream.processAnnotations(XXX.class);

這樣就算對方擴幾個字段這邊也不會有一點問題。

具體請參考:http://stackoverflow.com/questions/5377380/how-to-make-xstream-skip-unmapped-tags-when-parsing-xml

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章