title: Jackson ObjectMapper from MongoDB BSON
body: <p>I got a JSON that I serialize to a MongoDB <code>BasicDBObject</code> and insert it into the DB:</p>
  
  <pre><code>    String serialized = "";
      try {
          serialized = OBJECT_MAPPER.writeValueAsString(customEx.getOut().getBody());
      } catch (JsonProcessingException e) {
          e.printStackTrace();
      }
  
      collection.update(upsertQuery, BasicDBObject.parse(serialized), true, false);
  </code></pre>
  
  <p>On reading the <code>DBObject</code> from the DB I want to convert it to a POJO using the <code>ObjectMappers'</code> <code>readValue()</code> with a given class:</p>
  
  <pre><code>    public static &lt;T&gt; T fromDB(DBObject o, Class&lt;T&gt; clazz) {
      try {
          return OBJECT_MAPPER.readValue(o.toString(), clazz);
      } catch (IOException e) {
          e.printStackTrace();
      }
      return null;
  }
  </code></pre>
  
  <p>The class I want to convert it to is generated from an xsd sheme and also contains <code>timestamps</code>/<code>long</code> values as following:</p>
  
  <pre><code>@XmlRootElement(name = "ItemType")
  public class ItemType {
  
  @XmlSchemaType(name = "dateTime")
  protected XMLGregorianCalendar date;
  [...]
  </code></pre>
  
  <p>However this worked fine for older Java MongoDB versions. Now the long values are serialized as BSON looking like this:</p>
  
  <pre><code>"date": {
      "$numberLong": "1551172199214"
  }
  </code></pre>
  
  <p>When I try to deserialize this using jacksons <code>ObjectMapper</code> I get</p>
  
  <blockquote>
    <p>Cannot deserialize instance of <code>javax.xml.datatype.XMLGregorianCalendar</code> out of START_OBJECT token</p>
  </blockquote>
  
  <p>The reason for this is clear to me because the long value is in an own BSON - <code>Style</code> object.</p>
  
  <p>So far I already tried using <code>BsonDocument</code> like this:</p>
  
  <pre><code>public static &lt;T&gt; T fromDB(DBObject o, Class&lt;T&gt; clazz) {
      try {
          BsonDocument parse = BsonDocument.parse(o.toString());
          return OBJECT_MAPPER.readValue(parse.toJson(), clazz);
      } catch (IOException e) {
          e.printStackTrace();
      }
      return null;
  }
  </code></pre>
  
  <p>But that still does not convert the BSON parts to JSON.</p>
  
  <p>Is there any way to deserialize the BSON to a given Class using Jacksons <code>ObjectMapper</code>?
  Or just convert it to a <code>DBObject</code> without using BSON parts?</p>