使用 Jackson 与 Java Mongo DBObject 之间的高效 POJO 映射

虽然类似于使用MongoDB Java驱动程序将DBObject转换为POJO,但我的问题不同,因为我对使用Jackson进行映射特别感兴趣。

我有一个对象,我想将其转换为Mongo DBObject实例。我想使用Jackson JSON框架来完成这项工作。

一种方法是:

DBObject dbo = (DBObject)JSON.parse(m_objectMapper.writeValueAsString(entity));

但是,根据 https://github.com/FasterXML/jackson-docs/wiki/Presentation:-Jackson-Performance 这是最糟糕的方式。所以,我正在寻找一个替代方案。理想情况下,我希望能够挂接到 JSON 生成管道并动态填充实例。这是可能的,因为在我的案例中,目标是一个实例,它实现了 Map 接口。因此,它应该很容易地适应管道。DBObjectBasicDBObject

现在,我知道我可以使用该函数将对象转换为Map,然后使用该类型的map构造函数将map递归转换为实例。但是,我想知道我是否可以消除中间映射并直接创建。ObjectMapper.convertValueBasicDBObjectBasicDBObjectBasicDBObject

请注意,因为 a 本质上是一个映射,所以相反的转换,即从标量到 POJO 是微不足道的,应该非常有效:BasicDBObjectDBObject

DBObject dbo = getDBO();
Class clazz = getObjectClass();
Object pojo = m_objectMapper.convertValue(dbo, clazz);

最后,我的POJO没有任何JSON注释,我希望它保持这种方式。


答案 1

您可以使用Mixin注释来注释POJO和(或),因此注释不是问题。由于 是 地图,因此您可以在 put 方法上使用。BasicDBObjectDBObjectBasicDBOject@JsonAnySetter

m_objectMapper.addMixInAnnotations(YourMixIn.class, BasicDBObject.class);

public interface YourMixIn.class {
    @JsonAnySetter
    void put(String key, Object value);
}

这就是我所能想到的,因为我对MongoDB对象没有任何经验。

更新:MixIn基本上是一种Jackson机制,可以在不修改所述类的情况下向类添加注释。当您无法控制要封送的类(例如,当它来自外部jar时)或当您不想用注释使类混乱时,这是一个完美的选择。

在你的例子中,你说实现了接口,所以类具有映射接口定义的方法。通过向该方法添加@JsonAnySetter,您可以告诉 Jackson,每当他在类内省后发现他不知道的属性时,都可以使用该方法将该属性插入到对象中。键是属性的名称,值是属性的值。BasicDBObjectMapput

所有这些组合使得中间映射消失了,因为 Jackson 将直接转换为 the,因为它现在知道如何从 Json 反序列化该类。使用该配置,您可以执行以下操作:BasicDBOject

DBObject dbo = m_objectMapper.convertValue(pojo, BasicDBObject.class);

请注意,我还没有测试过这个,因为我不使用MongoDB,所以可能会有一些松散的结局。但是,我对类似的用例使用了相同的机制,没有任何问题。YMMV 取决于类。


答案 2

下面是一个简单的序列化程序(用 Scala 编写)从 POJO 到 BsonDocument 的示例,可以与 Mongo 驱动程序的版本 3 一起使用。反序列化程序的编写难度会稍大一些。

创建一个对象,该对象将直接对 Mongo Bson 执行流式序列化:BsonObjectGenerator

val generator = new BsonObjectGenerator
mapper.writeValue(generator, POJO)
generator.result()

下面是序列化程序的代码:

class BsonObjectGenerator extends JsonGenerator {

  sealed trait MongoJsonStreamContext extends JsonStreamContext

  case class MongoRoot(root: BsonDocument = BsonDocument()) extends MongoJsonStreamContext {
    _type = JsonStreamContext.TYPE_ROOT

    override def getCurrentName: String = null

    override def getParent: MongoJsonStreamContext = null
  }

  case class MongoArray(parent: MongoJsonStreamContext, arr: BsonArray = BsonArray()) extends MongoJsonStreamContext {
    _type = JsonStreamContext.TYPE_ARRAY

    override def getCurrentName: String = null

    override def getParent: MongoJsonStreamContext = parent
  }

  case class MongoObject(name: String, parent: MongoJsonStreamContext, obj: BsonDocument = BsonDocument()) extends MongoJsonStreamContext {
    _type = JsonStreamContext.TYPE_OBJECT

    override def getCurrentName: String = name

    override def getParent: MongoJsonStreamContext = parent
  }

  private val root = MongoRoot()
  private var node: MongoJsonStreamContext = root

  private var fieldName: String = _

  def result(): BsonDocument = root.root

  private def unsupported(): Nothing = throw new UnsupportedOperationException

  override def disable(f: Feature): JsonGenerator = this

  override def writeStartArray(): Unit = {
    val array = new BsonArray
    node match {
      case MongoRoot(o) =>
        o.append(fieldName, array)
        fieldName = null
      case MongoArray(_, a) =>
        a.add(array)
      case MongoObject(_, _, o) =>
        o.append(fieldName, array)
        fieldName = null
    }
    node = MongoArray(node, array)
  }

  private def writeBsonValue(value: BsonValue): Unit = node match {
    case MongoRoot(o) =>
      o.append(fieldName, value)
      fieldName = null
    case MongoArray(_, a) =>
      a.add(value)
    case MongoObject(_, _, o) =>
      o.append(fieldName, value)
      fieldName = null
  }

  private def writeBsonString(text: String): Unit = {
    writeBsonValue(BsonString(text))
  }

  override def writeString(text: String): Unit = writeBsonString(text)

  override def writeString(text: Array[Char], offset: Int, len: Int): Unit = writeBsonString(new String(text, offset, len))

  override def writeString(text: SerializableString): Unit = writeBsonString(text.getValue)

  private def writeBsonFieldName(name: String): Unit = {
    fieldName = name
  }

  override def writeFieldName(name: String): Unit = writeBsonFieldName(name)

  override def writeFieldName(name: SerializableString): Unit = writeBsonFieldName(name.getValue)

  override def setCodec(oc: ObjectCodec): JsonGenerator = this

  override def useDefaultPrettyPrinter(): JsonGenerator = this

  override def getFeatureMask: Int = 0

  private def writeBsonBinary(data: Array[Byte]): Unit = {
    writeBsonValue(BsonBinary(data))
  }

  override def writeBinary(bv: Base64Variant, data: Array[Byte], offset: Int, len: Int): Unit = {
    val res = if (offset != 0 || len != data.length) {
      val subset = new Array[Byte](len)
      System.arraycopy(data, offset, subset, 0, len)
      subset
    } else {
      data
    }
    writeBsonBinary(res)
  }

  override def writeBinary(bv: Base64Variant, data: InputStream, dataLength: Int): Int = unsupported()

  override def isEnabled(f: Feature): Boolean = false

  override def writeRawUTF8String(text: Array[Byte], offset: Int, length: Int): Unit = writeBsonString(new String(text, offset, length, "UTF-8"))

  override def writeRaw(text: String): Unit = unsupported()

  override def writeRaw(text: String, offset: Int, len: Int): Unit = unsupported()

  override def writeRaw(text: Array[Char], offset: Int, len: Int): Unit = unsupported()

  override def writeRaw(c: Char): Unit = unsupported()

  override def flush(): Unit = ()

  override def writeRawValue(text: String): Unit = writeBsonString(text)

  override def writeRawValue(text: String, offset: Int, len: Int): Unit = writeBsonString(text.substring(offset, offset + len))

  override def writeRawValue(text: Array[Char], offset: Int, len: Int): Unit = writeBsonString(new String(text, offset, len))

  override def writeBoolean(state: Boolean): Unit = {
    writeBsonValue(BsonBoolean(state))
  }

  override def writeStartObject(): Unit = {
    node = node match {
      case p@MongoRoot(o) =>
        MongoObject(null, p, o)
      case p@MongoArray(_, a) =>
        val doc = new BsonDocument
        a.add(doc)
        MongoObject(null, p, doc)
      case p@MongoObject(_, _, o) =>
        val doc = new BsonDocument
        val f = fieldName
        o.append(f, doc)
        fieldName = null
        MongoObject(f, p, doc)
    }
  }

  override def writeObject(pojo: scala.Any): Unit = unsupported()

  override def enable(f: Feature): JsonGenerator = this

  override def writeEndArray(): Unit = {
    node = node match {
      case MongoRoot(_) => unsupported()
      case MongoArray(p, a) => p
      case MongoObject(_, _, _) => unsupported()
    }
  }

  override def writeUTF8String(text: Array[Byte], offset: Int, length: Int): Unit = writeBsonString(new String(text, offset, length, "UTF-8"))

  override def close(): Unit = ()

  override def writeTree(rootNode: TreeNode): Unit = unsupported()

  override def setFeatureMask(values: Int): JsonGenerator = this

  override def isClosed: Boolean = unsupported()

  override def writeNull(): Unit = {
    writeBsonValue(BsonNull())
  }

  override def writeNumber(v: Int): Unit = {
    writeBsonValue(BsonInt32(v))
  }

  override def writeNumber(v: Long): Unit = {
    writeBsonValue(BsonInt64(v))
  }

  override def writeNumber(v: BigInteger): Unit = unsupported()

  override def writeNumber(v: Double): Unit = {
    writeBsonValue(BsonDouble(v))
  }

  override def writeNumber(v: Float): Unit = {
    writeBsonValue(BsonDouble(v))
  }

  override def writeNumber(v: BigDecimal): Unit = unsupported()

  override def writeNumber(encodedValue: String): Unit = unsupported()

  override def version(): Version = unsupported()

  override def getCodec: ObjectCodec = unsupported()

  override def getOutputContext: JsonStreamContext = node

  override def writeEndObject(): Unit = {
    node = node match {
      case p@MongoRoot(_) => p
      case MongoArray(p, a) => unsupported()
      case MongoObject(_, p, _) => p
    }
  }
}