c++ - 我需要帮助使用 RapidJSON

标签 c++ json rapidjson

我正在尝试使用 RapidJSON 解析一个 JSON 文件,其中有数千个像这样的对象

"Amateur Auteur": {
"layout": "normal",
"name": "Amateur Auteur",
"manaCost": "{1}{W}",
"cmc": 2,
"colors": [
  "White"
],
"type": "Creature — Human",
"types": [
  "Creature"
],
"subtypes": [
  "Human"
],
"text": "Sacrifice Amateur Auteur: Destroy target enchantment.",
"power": "2",
"toughness": "2",
"imageName": "amateur auteur",
"colorIdentity": [
  "W"
 ]
},

我相信我已经将 JSON 正确地存储为 C 字符串我只是无法真正理解如何使用 RapidJSON 库从每个对象返回我想要的值。

这是将 JSON 存储为 C 字符串然后解析它以防我在这里做错事情的代码。

std::ifstream input_file_stream;
input_file_stream.open("AllCards.json", std::ios::binary | std::ios::ate); //Open file in binary mode and seek to end of stream 

if (input_file_stream.is_open())
{
    std::streampos file_size = input_file_stream.tellg(); //Get position of stream (We do this to get file size since we are at end)
    input_file_stream.seekg(0); //Seek back to beginning of stream to start reading
    char * bytes = new char[file_size]; //Allocate array to store data in
    if (bytes == nullptr)
    {
        std::cout << "Failed to allocate the char byte block of size: " << file_size << std::endl;
    }
    input_file_stream.read(bytes, file_size); //read the bytes
    document.Parse(bytes);
    input_file_stream.close(); //close file since we are done reading bytes
    delete[] bytes; //Clean up where we allocated bytes to prevent memory leak
}
else
{
    std::cout << "Unable to open file for reading.";
}

最佳答案

您的帖子似乎提出了多个问题。让我们从头开始。

I believe I have stored the JSON as a C string correctly I just can't really understand how to use the RapidJSON library to return the values I want from each object.

这是软件工程中的一个大禁忌。永远不要相信或假设。它会在发布日回来并困扰你。而是验证您的断言。以下是从简单到复杂的几个步骤。

  1. 打印出您的 C 字符串。

确认变量内容(尤其是字符串数据)的最简单方法是简单地打印到屏幕上。没有什么比看到您的 JSON 数据打印到屏幕上以确认您已正确读取它更容易的了。

std::cout.write(bytes, filesize);
  1. 断点/调试器

如果你有一些原因不打印出你的变量,然后编译你的代码并启用调试并加载到 GDB 如果你使用 g++, lldb 如果您使用的是 clang++,或者如果您使用的是 VS 或 VSCode,则只需在 visual studio 中放置一个断点。到达断点后,您可以检查变量的内容。

但是,在我们继续之前,如果我没有指出在 CPP 中读取文件比您正在阅读的方式要容易得多,我就不会帮助您。

    // Open File
    std::ifstream in("AllCards.json", std::ios::binary);
    if(!in)
        throw std::runtime_error("Failed to open file.");

    // dont skip on whitespace
    std::noskipws(in);

    // Read in content
    std::istreambuf_iterator<char> head(in);
    std::istreambuf_iterator<char> tail;
    std::string data(head, tail);

在上述代码的末尾,您现在已将文件中的所有内容读入 std::string,它包装了一个空终止符或 C 字符串。您可以通过在字符串实例上调用 .c_str() 来访问该数据。如果你这样做,你就不必再担心调用 newdelete[] 因为 std::string 类会处理给你的缓冲区。只需确保只要您在 RapidJSON 中使用它,它就会一直存在。

This is the code for storing the JSON as a C string and then parsing it in case I am doing something incorrect here.

没有。根据快速 JSON 文档,您创建一个文档对象并让它解析字符串。

Document d;
d.Parse(data.c_str());

但是,这只是创建用于查询文档的元素。您可以询问文档是否存在特定项 (d.hasMember("")),询问字符串类型的成员内容 d["name"].GetString()或文档中列出的任何内容。可以看教程here .

顺便说一下。欢迎来到 SO。我建议您下次发帖时问一个更有针对性的问题。你到底想用解析后的 JSON 元素做什么?

I just can't really understand how to use the RapidJSON library to return the values I want from each object.

我不能回答这个问题有两个原因。你想提取什么?你试过什么?您是否阅读了文档并且不了解特定项目?

这里是阅读有关提出更好问题的好地方。请不要以为我在贬低你。我提出这个问题是因为提出更好的问题会让你得到更好、更具体的答案。问得不好的问题总是有被忽视的风险,或者,我敢说,好的老式does google not work today 响应。

https://stackoverflow.com/help/how-to-ask

** 更新 ** 对于你的问题。您可以遍历所有对象。

 using namespace rapidjson;
     Document d;
     d.Parse(data.c_str());
     for (auto itr = d.MemberBegin(); itr != d.MemberEnd(); ++itr){
             std::cout << itr->name.GetString() << '\n';
     }

关于c++ - 我需要帮助使用 RapidJSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49542209/

相关文章:

c++ - std::vector::insert,以 end 作为第一个参数调用它可以吗?

c++ - 如何使用 C++ std::barrier arrival_token?

json - 如何从 Elasticsearch 中的 "OR"查询中生成逻辑 "bool"?

java - 如何将 JSON 字符串存储为实体的属性

c++ - RapidJSON:用汉字写字符串

c++ - QML:如何检索默认字体对象?

c++ - OpenCV:使用霍夫圆变换检测虹膜

jquery - Shopify jquery ajax api,addItem()返回成功,但购物车未显示正确的商品数量

floating-point - 使用 RapidJSON 舍入 double 类型

c++ - 比较 rapidjson::Documents