2012-12-28 2 views
8

JSONのシリアル化/逆シリアル化にジャクソン(2.1.1)を使用しています。 JAXBアノテーションを持つ既存のクラスがあります。これらの注釈のほとんどは正しいもので、そのままjacksonで使用することができます。私はmix-insを使ってこれらのクラスの逆直列化/直列化を少し変更しています。私ObjectMapperコンストラクタでジャクソンJaxbアノテーションの優先順位 - @XmlTransientをオーバーライドする@JsonProperty

私は次のようにします。上記に基づき

setAnnotationIntrospector(AnnotationIntrospector.pair(
       new JacksonAnnotationIntrospector(), 
       new JaxbAnnotationIntrospector(getTypeFactory()))); 

を、ジャクソン注釈があるためintrospectorsのオーダーで、JAXBよりも優先されます。これはJackson Jaxb docsに基づいています。私が無視したいフィールドの場合、mix-inのフィールドに@JsonIgnoreを追加するとうまくいきます。私が無視したくない既存のクラスの中に@XmlTransientとしてマークされているフィールドがいくつかあります。私は@JsonPropertyをミックスインのフィールドに追加しようとしましたが、動作しないようです。ここで

が元のクラスです:

public interface FooMixIn { 
    @JsonIgnore String getBaz(); //ignore the baz property 
    @JsonProperty String getBar(); //override @XmlTransient with @JsonProperty 
} 

元のクラスを変更することなく、これを解決する方法任意のアイデア:

public class Foo { 
    @XmlTransient public String getBar() {...} 
    public String getBaz() {...} 
} 

ここでミックスインはありますか?

私はまた、代わりにミックスインを使用してのメンバーに@JsonPropertyを追加テスト:

public class Foo { 
    @JsonProperty @XmlTransient public String getBar() {...} 
    @JsonIgnore public String getBaz() {...} 
} 

私はミックスインと同じように同じ動作を得るように見えます。 @XmlTransientが削除されない限り、プロパティは無視されます。

答えて

7

問題がいずれかのイントロスペクタは、マーカーを無視検出した場合AnnotationIntrospectorPair.hasIgnoreMarker()メソッドは、基本的に@JsonPropertyを無視することである:

public boolean hasIgnoreMarker(AnnotatedMember m) { 
     return _primary.hasIgnoreMarker(m) || _secondary.hasIgnoreMarker(m); 
    } 

REF:github

問題を回避するにはにJaxbAnnotationIntrospectorをサブクラス化することを希望の動作を得る:

public class CustomJaxbAnnotationIntrospector extends JaxbAnnotationIntrospector { 
    public CustomJaxbAnnotationIntrospector(TypeFactory typeFactory) { 
     super(typeFactory); 
    } 

    @Override 
    public boolean hasIgnoreMarker(AnnotatedMember m) { 
     if (m.hasAnnotation(JsonProperty.class)) { 
      return false; 
     } else { 
      return super.hasIgnoreMarker(m); 
     } 
    } 
} 

CustomJaxbAnnotationIntrospectorAnnotationIntrospectorPair

関連する問題