2016-06-01 11 views
2

私はjava spring mvcプロジェクトに取り組んでいます。私はクラスを拡張してObjectMapperという形式のjacksonを作成しました。また、私はCustomObjectMapperを春の設定に設定しています。だから、jacksonがserializeまたはdeserializeを望むたびに、私のCustomObjectMapperが動作し、すべてが正しいです。しかし、私は1つの問題があります:jacksonデシリアライザ - モデルフィールドの注釈リストを取得

私はカスタム注釈@AllowHtmlを作成しました。私はそれを私のモデルのいくつかのStringフィールドの上に置きました。また、私はこの方法でJsonDeserializerStringクラスを作成しました:

public class JsonDeserializerString extends JsonDeserializer<String>{ 

    @Override 
    public String deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { 

     return jp.getText(); 
    } 

} 

そして、私はこのように私のCustomObjectMapperでこのデシリアライザを設定します。

@Component 
public class CustomObjectMapper extends ObjectMapper { 
    public CustomObjectMapper(){ 
     SimpleModule module = new SimpleModule(); 
     module.addDeserializer(String.class, new JsonDeserializerString()); 
     this.registerModule(module); 
    } 
} 

これは期待通りに動作し、ユーザーがフォームを送信すると、すべての文字列フィールドはJsonDeserializerStringで逆シリアル化されます。しかし、私はにデシリアライザのフィールドアノテーションを取得したいと思います。。実際には、私はしたい、文字列フィールドにモデル内の特定の注釈がある場合、いくつかの論理を行います。これどうやってするの?

答えて

1

デシリアライザでContextualDeserializerを実装し、プロパティの注釈を抽出することができます。それをプライベートプロパティに格納し、Stringを直列化解除している間に再利用することができます。

例:

public class EmbeddedDeserializer 
    extends JsonDeserializer<Object> 
    implements ContextualDeserializer { 

    private Annotation[] annotations; 

    @Override 
    public JsonDeserializer<?> createContextual(final DeserializationContext ctxt, 
     final BeanProperty property) throws JsonMappingException { 

     annotations = property.getType().getRawClass().getAnnotations(); 

     return this; 
    } 

    @Override 
    public Object deserialize(final JsonParser jsonParser, 
     final DeserializationContext context) 
      throws IOException, JsonProcessingException { 

      if (annotations contains Xxxx) { ... } 
     } 
} 

私はそれが役に立てば幸い。

関連する問題