【问题标题】:libbson help to read data into object C++libbson 帮助将数据读入对象 C++
【发布时间】:2021-08-03 15:53:42
【问题描述】:

我的虚幻项目必须将一些 BSON 文档数据读出到地图中。

现在我可以加载该文件并使用以下代码将其打印出来:

void AMyActor::BeginPlay()
{
    Super::BeginPlay();

    std::ifstream input( filePath , std::ios::binary );
    std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});

    bson_t* doc{ bson_new_from_data(buffer.data(),buffer.size()) };
    char *str;
    if( doc != nullptr )
    {
        UE_LOG(LogTemp,Warning,TEXT( "Success" ));

        str = bson_as_json(doc, NULL);
        
        FString fstr = FString(UTF8_TO_TCHAR(str));
        
        UE_LOG(LogTemp, Warning, TEXT("BSON Output: %s"), *fstr);       
    }
}

这是我想要存储它的地方:

class Databases
{
    std::map<std::string,DatabaseBase> _dictionary;

    explicit Databases(const std::map<std::string, DatabaseBase>& dictionary)
        : _dictionary(dictionary)
    {
    }
};

所以我正在寻找的是创建一个新的数据库实例并使用 bson 文档的内容初始化“_dictionary”。

我实际上是在 libbson 文档中寻找这个:http://mongoc.org/libbson/current/bson_t.html

但没有成功...有人可以帮助我吗?

先谢谢了

PS:我在虚幻之下,但我已经链接了 libbson 库

更新: 因为我必须提供我的 json 文件的样子,以及 DatabaseBase 的样子

JSON:

{
  "_dictionary" : [ {
      "_classID" : "CC00",
      "_dictionary" : [ {
          "k" : "sample_key",
          "v" : ["ACH_00"]
        }, {
          "k" : "sample_index",
          "v" : ["0"]
        }]
    }, {
      "_classID" : "CC01",
      "_dictionary" : [ {
          "k" : "sample_key",
          "v" : ["ACH_01"]
        }, {
          "k" : "sample_index",
          "v" : ["1"]
        }]
    }]
}

数据库:

class DatabaseBase
{
public:
    DatabaseBase() = default;

    std::string sample_key;
    int sample_index; 
};

【问题讨论】:

  • 您能解释一下如何从 JSON 文档中初始化 DatabaseBase 对象吗? (即 JSON 文档中有什么?)
  • 它是一个包含整数、字符串和枚举等值的类
  • 那我不知道你的问题是什么。您将 BSON 转换为 JSON;虚幻引擎不支持解析JSON吗?或者,您可以直接使用 BSON。
  • 我要做的是将包含在 bson 文件中的整个文档存储到 _dictionary 映射中。在 c# 中很容易做到,但在 C++ 中则不行,而且没有很好的文档记录
  • 我们无法告诉您如何在不知道该类型或映射是什么样子的情况下将任意 BSON/JSON 值转换为 DatabaseBase。您对通用的 Json::Value 类型或其他类型感到满意吗?

标签: c++ mongodb bson


【解决方案1】:

爆出nlohmann::json

    using nlohmann::json;
    std::map<std::string, DatabaseBase> dictionaries;
    json input = json::from_bson(buffer);
    for (auto& obj : input["_dictionary"]) {
        auto name = obj["_classID"];
        auto key = obj["_dictionary"][0]["v"][0];
        auto idx = stoi(obj["_dictionary"][1]["v"][0].get<std::string>());
        auto db = DatabaseBase{key, idx};
        dictionaries[name] = db;
    }
    Databases dbs{dictionaries};

输出:(来自我的调试器)

(lldb) p dbs
(Databases) $0 = {
  _dictionary = size=2 {
    [0] = {
      first = "CC00"
      second = (sample_key = "ACH_00", sample_index = 0)
    }
    [1] = {
      first = "CC01"
      second = (sample_key = "ACH_01", sample_index = 1)
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 2012-05-07
    • 2020-05-28
    • 1970-01-01
    相关资源
    最近更新 更多