title: (De-)Serialize Bean in a custom way at runtime
body: <p>Let's imagine I have the following POJO:</p>
  
  <pre><code>class Pojo {
      String s;
      Object o;
      Map&lt;String, String&gt; m;
  }
  </code></pre>
  
  <p>And at runtime, I want default serialization / deserialization for all properties except one. Typically, I want to replace a field by its ID in a database when serializing, similarly to <a href="https://stackoverflow.com/questions/5325096/deserializing-entities-with-relationships">this other question</a>.</p>
  
  <p>For example, I want to replace <code>o</code> by a string obtained from an external mapping (for example: <code>object1</code> &lt;=> "123" and <code>object2</code> &lt;=> "456"):</p>
  
  <ul>
  <li>serialization: read <code>o</code> and replace (so if <code>o</code> is <code>object1</code>, serialize as string "123")</li>
  <li>deserialization: read "123", query some table to get the original value of <code>o</code> back (i.e. <code>object1</code>), recreate a <code>Pojo</code> object with <code>o = object1</code>.</li>
  </ul>
  
  <p>I understand that Modules would be one way to do that but I'm not sure how to use them while keeping the automatic BeanSerializer/Deserializer for the properties that don't need to be changed.</p>
  
  <p>Can someone give an example (even contrived) or an alternative approach?</p>
  
  <hr>
  
  <p>Notes:</p>
  
  <ul>
  <li>I can't use annotations or Mixins as the changes are unknown at compile time (i.e. any properties might be changed in a way that is not determinable).</li>
  <li><a href="https://stackoverflow.com/questions/2981359/jackson-suppressing-serializationwrite-of-properties-dynamically">This other question</a> points to using a CustomSerializerFactory, which seems to do the job. Unfortunately, the official site indicates that <a href="http://wiki.fasterxml.com/CustomSerializerFactory" rel="nofollow noreferrer">it is not the recommended approach any more</a> and that modules should be used instead.</li>
  </ul>
  
  <hr>
  
  <p><strong>Edit</strong></p>
  
  <p>To be a little clearer, I can do the following with Mixins for example:</p>
  
  <pre><code>ObjectMapper mapper = new ObjectMapper(MongoBsonFactory.createFactory());
  mapper.addMixInAnnotations(Pojo.class, PojoMixIn.class);
  
  ObjectReader reader = mapper.reader(Pojo.class);
  DBEncoder dbEncoder = DefaultDBEncoder.FACTORY.create();
  OutputBuffer buffer = new BasicOutputBuffer();
  dbEncoder.writeObject(buffer, o);
  </code></pre>
  
  <p>with the following Mixin:</p>
  
  <pre><code>abstract class PojoMixIn {
      @JsonIgnore Object o;
  }
  </code></pre>
  
  <p>And then add the required string to the JSON content. But I would need to know at compile time that it is the <code>o</code> field that needs to be replaced, which I don't.</p>