2016-07-19 3 views
0

1つのコントローラでのみいくつかの属性をフィルタリングする必要があります。JsonFilterでフィルターされた帰属属性をSpring Controllerに含めるにはどうすればよいですか?

Fasterxml JsonFilterは私が

​​

のようなオブジェクトを使用すると

FilterProvider filter2 = new SimpleFilterProvider().addFilter("somefilter", 
SimpleBeanPropertyFilter.filterOutAllExcept("prop1","prop2")); 

をたどるように、コントローラにObjectMapperとそれを使用したときに動作しますが、春のコントローラ

@RequestMapping(value = "/path", method = RequestMethod.GET) 
    protected @ResponseBody Foo handleGet(.. 
と同じオブジェクトを返すようにしようとしたとき

public class Foo{ 
Bar p1; 
Bar p2; 
} 

Bar属性は完全に省略されています。この場合、オブジェクトをフィルタ処理なしで返す必要があります。

オブジェクト全体を返すためにコントローラのオブジェクトマッパーを使用する必要があります。

コントローラのフィルタを無効にする方法はありますか?

+0

あなたは、シリアル化されるBarオブジェクトのいくつかのフィールドをスキップしようとしていますか? –

+0

はい、ObjectMapperを使用すると、シリアライズをスキップします。しかし、コントローラ内のすべてをシリアル化してください。 –

+0

コントローラがそれを使用するとき、フィールドを表示しますか?申し訳ありませんが、以前のコメントを編集することはできません。 –

答えて

1

MappingJacksonValueを試して、ジャクソンフィルタプロバイダを設定して、SpringコントローラでPOJOをシリアル化することができます。 AbstractJackson2HttpMessageConverterのソースコードから

protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) 
     throws IOException, HttpMessageNotWritableException { 
    ... 
    try { 
     ... 
     if (object instanceof MappingJacksonValue) { 
      MappingJacksonValue container = (MappingJacksonValue) object; 
      ... 
      filters = container.getFilters(); 
     } 
     ... 
     ObjectWriter objectWriter; 
     if (serializationView != null) { 
      objectWriter = this.objectMapper.writerWithView(serializationView); 
     } 
     else if (filters != null) { 
      objectWriter = this.objectMapper.writer(filters); 
     } 
     else { 
      objectWriter = this.objectMapper.writer(); 
     } 
     ... 
     objectWriter.writeValue(generator, value); 
     ... 
    } 

MappingJacksonValueに設定されたフィルタによってobjectMapperFilterProviderをリセットすることが可能です。以下のようなあなたのケースでは、あなたが何かを試すことができます:あなたが唯一のBarからプロパティをフィルタリングするために必要とする1つのコントローラを持っている場合は

@RequestMapping(value = "/foo", method = RequestMethod.GET) 
protected @ResponseBody MappingJacksonValue handleGet(...) { 
    MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(foo);  
    FilterProvider filter = new SimpleFilterProvider().addFilter("somefilter", SimpleBeanPropertyFilter.serializeAllExcept()); 
    mappingJacksonValue.setFilters(filter); 
    return mappingJacksonValue; 
} 

は、あなたもObjectMapperにそれを設定するのではなく、特定のコントローラ用のフィルタを追加することを検討して:

@RequestMapping(value = "/bar", method = RequestMethod.GET) 
protected @ResponseBody MappingJacksonValue handleGet(...) { 
    MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(bar);  
    FilterProvider filter = new SimpleFilterProvider().addFilter("somefilter", SimpleBeanPropertyFilter.filterOutAllExcept("prop1","prop2")); 
    mappingJacksonValue.setFilters(filter); 
    return mappingJacksonValue; 
} 
関連する問題