title: How to include only specific properties when serializing with Jackson
body: <p>I am trying to implement a universal method which serializes the given object to JSON, but only those properties which are passed in a collection. If possible I want to get this functionality without specifying <code>@JsonFilter</code> on the class. For this I am trying to use <a href="http://fasterxml.github.io/jackson-databind/javadoc/2.4/com/fasterxml/jackson/databind/ser/impl/SimpleBeanPropertyFilter.FilterExceptFilter.html" rel="noreferrer"><code>FilterExceptFilter</code></a> from Jackson 2.4.1. Dependencies:</p>
  
  <ul>
  <li><a href="http://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.4.1" rel="noreferrer">jackson-core-2.4.1.jar</a></li>
  <li><a href="http://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.4.1" rel="noreferrer">jackson-databind-2.4.1.jar</a></li>
  <li><a href="http://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations/2.4.0" rel="noreferrer">jackson-annotations-2.4.0.jar</a></li>
  </ul>
  
  <p>Here is what I have at the moment:</p>
  
  <pre class="lang-java prettyprint-override"><code>public static String serializeOnlyGivenFields(Object o,
                      Collection&lt;String&gt; fields) throws JsonProcessingException {
      if ((fields == null) || fields.isEmpty()) return null;
  
      Set&lt;String&gt; properties = new HashSet&lt;String&gt;(fields);
  
      SimpleBeanPropertyFilter filter =
          new SimpleBeanPropertyFilter.FilterExceptFilter(properties);
      SimpleFilterProvider fProvider = new SimpleFilterProvider();
      fProvider.addFilter("fieldFilter", filter);
      fProvider.setDefaultFilter(filter);
  
      ObjectMapper mapper = new ObjectMapper();
      mapper.setFilters(fProvider);
  
      String json = mapper.writeValueAsString(o);
      return json;
  }
  </code></pre>
  
  <p>However, the filter is never applied. It always serializes all properties.</p>
  
  <pre class="lang-java prettyprint-override"><code>Set&lt;String&gt; fields = new HashSet&lt;String&gt;(); fields.add("name");
  String json = Serializer.serializeOnlyGivenFields(e, fields);
  System.out.println(json);
  </code></pre>
  
  <blockquote>
    <p>{"name":"Test entity","description":"Test description"}</p>
  </blockquote>
  
  <p>I have also tried to register the <a href="http://fasterxml.github.io/jackson-databind/javadoc/2.4/com/fasterxml/jackson/databind/ObjectMapper.html#writer(com.fasterxml.jackson.databind.ser.FilterProvider)" rel="noreferrer"><code>FilterProvider</code> on the <code>ObjectWriter</code></a>, but same result:</p>
  
  <pre><code>String json = mapper.writer(fProvider).writeValueAsString(o);
  </code></pre>
  
  <p>What am I missing? Is there a nice way to achieve this with Jackson?</p>