当需要存储以Java实例形式(来自生成的Java类)的protobuf3消息时,最好的选择是存储对象本身,然后再从数据库中读取它。
我的用例是将此类消息存储在Mongodb中。在调查此问题时,我找不到办法,因此决定在这里询问。
您可以将Protobufs Java类转换为JSON,然后从JSON转换为org.bson.Document
,然后编写文档并在读取时反转该转换。
有关更多详细信息,请参见JsonFormat。
这是写端的一个简单示例:
YourProtobufsClass anInstance = YourProtobufsClass.getDefaultInstance();
String json = JsonFormat.printer().print(yourProtobufsClass);
Document document = Document.parse(json);
mongoClient.getDatabase(...).getCollection(...).insertOne(document);
这是读取端的一个简单示例:
JsonFormat.Parser parser = JsonFormat.parser();
FindIterable<Document> documents = collection.find(...);
for (Document document : documents) {
YourProtobufsClass.Builder builder = YourProtobufsClass.newBuilder();
parser.merge(document.toJson(), builder);
// now you can build an instance of your protobufs class which
// has been populated from the retrieved JSON
YourProtobufsClass anInstance = builder.build();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句