2011-10-27 25 views
7

我有一個有十幾個屬性的類。對於基本類型的大多數屬性,我希望使用默認的BeanSerializer和BeanDeserializer或其他來減少我需要編寫的繁瑣代碼。對於自定義和數組類型的其他屬性,我想做一些自定義的串行器/解串器。請注意,我無法更改基礎JSON字符串。但是我完全可以訪問android代碼。我正在使用傑克遜1.7.9/Ektorp 1.1.1。如何在Jackson中編寫自定義串行器和解串器?

我應該繼承BeanDeserializer嗎?我遇到了麻煩。它期望一個沒有參數的默認構造函數,但我不知道如何調用超級構造函數。

class MyType{ 
    // a dozen properties with primitive types String, Int, BigDecimal 
    public Stirng getName(); 
    public void setName(String name); 

    // properties that require custom deserializer/serializer 
    public CustomType getCustom(); 
    public void setCustom(CustomType ct); 
} 

class MyDeserializer extends BeanDeserialzer{ 
    // an exception is throw if I don't have default constructor. 
    // But BeanDeserializer doesn't have a default constructor 
    // It has the below constructor that I don't know how to fill in the parameters 
    public MyDeserializer(AnnotatedClass forClass, JavaType type, 
     BeanProperty property, CreatorContainer creators, 
     BeanPropertyMap properties, 
     Map<String, SettableBeanProperty> backRefs, 
     HashSet<String> ignorableProps, boolean ignoreAllUnknown, 
     SettableAnyProperty anySetter) { 
    super(forClass, type, property, creators, properties, backRefs, ignorableProps, 
      ignoreAllUnknown, anySetter); 
} 
    @Override 
    public Object deserialize(JsonParser jp, DeserializationContext dc, Object bean) 
     throws IOException, JsonProcessingException { 
    super.deserialize(jp, dc, bean); 
     MyType c = (MyType)bean;   

      ObjectMapper mapper = new ObjectMapper(); 

      JsonNode rootNode = mapper.readValue(jp, JsonNode.class); 
      // Use tree model to construct custom 
      // Is it inefficient because it needs a second pass to the JSON string to construct the tree? 
      c.setCustom(custom); 
      return c; 
} 
} 

我搜索了Google,但找不到任何有用的示例/教程。如果任何人都可以寄給我一些很棒的例子!謝謝!

回答

4

對於BeanSerializer/-Deserializer子類,最好使用更新版本的Jackson,因爲通過BeanSerializerModifier和BeanDeserializerModifier的顯式支持可以改進此區域,這可以改變實例的配置。

但只是爲了確保,你還可以指定自定義的串行器/解串器只是個人性質使用,就像這樣:

class Foo { 
    @JsonSerialize(using=MySerializer.class) 
    public OddType getValue(); 
} 
+0

感謝您的想法!我會試試看看它是否有效。我使用Ektorp for Android,他們建議使用1.1.1,這就是爲什麼我使用Jackson 1.7.9。但如果我升級它可能會工作。 –

+0

我可以去的最高版本是1.8.5。任何建議?我將在OddType上試用你的JsonSerializer的想法。 –

+0

1.8比1.7有更好的可重寫性,所以它可能實際上工作。使用BeanSerializerModifier你實際上不需要重寫BeanSerializer,但也可以創建自定義實例,但將其他道具推遲到默認設置。另外,你的自定義序列化器可以在'resolve()'方法中查找默認的序列化器(如果你實現了ResolvableSerializer,類似於BeanSerializer的做法)。理想情況下,如果可能的話,你會避免對BeanSerializers進行子類化,只是爲了簡單;但是如果你需要子類,那也是一種支持的技術。 – StaxMan