将DBRef解析为Json

8

我在 MongoDB 的标准化数据模型结构中遇到了以下错误:

org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class com.mongodb.DBRef

这是由以下代码引起的:

System.out.println(document.toJson());

具体来说,是关于toJson()的部分。我有一个包含DBRef对象的文档,因此我可以从另一个集合中引用文档。嵌入式文档结构不是选项。那么我该如何解决这个问题呢?

2个回答

7
你需要导入DBRef编解码器才能打印它,如果你想以文档JSON格式呈现它,你需要编写自己的DBRef编解码器并将其添加到codecregistry中,然后再使用toJson()方法。
例如:
CodecRegistry codecRegistry = MongoClientSettings.getDefaultCodecRegistry();
-------
final DocumentCodec codec = new DocumentCodec(codecRegistry, new BsonTypeClassMap());
-------
System.out.println(document.toJson(codec));

0

由于这是在谷歌搜索错误时的第一个结果,而且被接受的答案中提供的解决方案似乎并不直观,并且由于MongoClient不再具有getDefaultCodecRegistry()方法,因此不再起作用,所以我将发布帮助我的内容:

    protected MongoCollection<Document> collection;

      private final CodecRegistry DEFAULT_REGISTRY = CodecRegistries.fromProviders(
          asList(new ValueCodecProvider(),
              new BsonValueCodecProvider(),
              new DocumentCodecProvider(),
              new DBRefCodecProvider(),
              new DBObjectCodecProvider(),
              new BsonValueCodecProvider(),
              new GeoJsonCodecProvider(),
              new GridFSFileCodecProvider()));

      private final BsonTypeClassMap DEFAULT_BSON_TYPE_CLASS_MAP = new BsonTypeClassMap();

      private final DocumentCodec documentCodec = new DocumentCodec(
          DEFAULT_REGISTRY,
          DEFAULT_BSON_TYPE_CLASS_MAP
      );
-----------------------------------------------------------------------
JsonWriterSettings writerSettings = org.bson.json.JsonWriterSettings.
        builder().
        outputMode(JsonMode.SHELL).
        indent(true)
        .build();

    JsonArray jsonArray = new JsonArray();
    collection.
        find().
        iterator().
        forEachRemaining(entry -> jsonArray.add(new JsonParser().parse(entry.toJson(writerSettings, documentCodec)).getAsJsonObject()));

解决方案来自于这里:https://github.com/akitoshka/debezium/commit/8dd12d76acced74de7ab184bc18a4384565a70b7


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接