2012-03-06 48 views
1

我收到來自Web服務的JSON響應,但出於各種原因,我不想在最終響應對象中反序列化某些屬性。例如,我有:FlexJSON在反序列化時排除屬性

public class Foo { 
    private String bar; 
    private int baz; 

    //getters & setters 
} 

我找回JSON響應有兩個屬性,但在反序列化,我不想要的「欄」進行設置。原因是他們發送的屬性很長,但是我們的是一個String,所以反序列化拋出IllegalArgumentException。

另一種選擇是使用類似json-simple的方式解析JSON,刪除我想要的屬性,將其轉換回JSON並傳入解串器,但是我想避免這種情況,因爲JSON非常大。

有沒有辦法用ObjectFactory來做到這一點?

回答

2

是的,ObjectFactory可以用來允許從長轉換爲字符串。只需註冊的ObjectFactory您的路徑就像:

new JSONDeserializer().use("some.path.to.bar", new EnhancedStringObjectFactory()).deserialize(json, new SomeObject()); 



public class EnhancedStringObjectFactory implements ObjectFactory { 
    public Object instantiate(ObjectBinder context, Object value, Type targetType, Class targetClass) { 
     if(value instanceof String) { 
      return value; 
     } else if(value instanceof Number) { 
      return ((Number)value).toString(); 
     } else { 
      throw context.cannotConvertValueToTargetType(value, String.class); 
     } 
    } 
} 

你甚至可以註冊一個作爲字符串默認的ObjectFactory,它會處理這種情況的到來到解串器的任何字符串:

new JSONDeserializer().use(String.class, new EnhancedStringObjectFactory()).deserialize(json, new SomeObject());