title: jackson custom serialization with filtering
body: <p>I need to customize serialization of a POJO in Jackson so that I can apply filter on the  properties based on user input </p>
  
  <p>I applied the following annotations on the POJO.</p>
  
  <pre><code>@JsonFilter("userFilter")
  @JsonSerialize(using = UserSerializer.class)
  </code></pre>
  
  <p>The custom serializer class is as below.</p>
  
  <pre><code>public class UserSerializer  extends JsonSerializer&lt;User&gt; {
  
  
      @Override
      public void serialize(User value, JsonGenerator jgen,
              SerializerProvider provider) throws IOException,
              JsonProcessingException {
  
          ObjectMapper mapper = new ObjectMapper();
          SimpleFilterProvider sfp = new SimpleFilterProvider();
  
          // create a  set that holds name of User properties that must be serialized
          Set userFilterSet = new HashSet&lt;String&gt;();
          userFilterSet.add("firstName");
          userFilterSet.add("corporateOrgs");
          userFilterSet.add("rights");
          userFilterSet.add("requirements");
  
  
          sfp.addFilter("userFilter",SimpleBeanPropertyFilter.filterOutAllExcept(userFilterSet));
  
          // create an objectwriter which will apply the filters 
          ObjectWriter writer = mapper.writer(sfp);
  
          String json = writer.writeValueAsString(value);
  
  
      }
  
  }
  </code></pre>
  
  <p>I can see that Jackson is trying to serialize the POJO using the custom serializer defined. However it ends up in infinite recursion/stackoverflow as <code>writer.writeValueAsString(value)</code> ends up calling the custom serializer again.</p>
  
  <p>Obviously I have not got some basic stuff right here. If the filtering is done outside the serialize method (for example in a method called from <code>main()</code> ), filtering works as expected.</p>
  
  <p>can anyone please provide insight/link to documentation on how to make use of custom serialization to leverage filtering.</p>