【问题标题】:How to read a json file into a C++ string如何将 json 文件读入 C++ 字符串
【发布时间】:2012-12-18 14:44:23
【问题描述】:

我的代码是这样的:

std::istringstream file("res/date.json");
std::ostringstream tmp;
tmp<<file.rdbuf();
std::string s = tmp.str();
std::cout<<s<<std::endl;

输出是res/date.json,而我真正想要的是这个json文件的全部内容。

【问题讨论】:

  • 您必须打开文件,然后将其内容读入std::string
  • 应该使用 ifstream,而不是 istringstream。
  • 使用ifstream,而不是istringstream

标签: c++ json string fstream


【解决方案1】:

这个

std::istringstream file("res/date.json");

创建一个从字符串"res/date.json"读取的流(名为file)。

这个

std::ifstream file("res/date.json");

创建一个从名为 res/date.json 的文件中读取的流(名为 file)。

看到区别了吗?

【讨论】:

    【解决方案2】:

    我后来找到了一个很好的解决方案。在fstream 中使用parser

    std::ifstream ifile("res/test.json");
    Json::Reader reader;
    Json::Value root;
    if (ifile != NULL && reader.parse(ifile, root)) {
        const Json::Value arrayDest = root["dest"];
        for (unsigned int i = 0; i < arrayDest.size(); i++) {
            if (!arrayDest[i].isMember("name"))
                continue;
            std::string out;
            out = arrayDest[i]["name"].asString();
            std::cout << out << "\n";
        }
    }
    

    【讨论】:

    • 如何在我的 c++ 项目中拥有Json::Reader
    【解决方案3】:

    .json 文件加载到std::string 中并将其写入控制台:

    #include <iostream>
    #include <string>
    #include <fstream>
    #include <sstream>
    
    int main(int, char**) {
    
        std::ifstream myFile("res/date.json");
        std::ostringstream tmp;
        tmp << myFile.rdbuf();
        std::string s = tmp.str();
        std::cout << s << std::endl;
    
        return 0;
    }
    

    【讨论】:

    • 我的 json 解析器使用此方法失败,但如果我将 json 文本直接手动写入字符串,它可以工作......这对文本格式有什么作用?
    【解决方案4】:

    我尝试了上面的东西,但问题是它们不适用于我的 C++ 14 :P 我从 ifstream incomplete type is not allowedon 两个答案和 2 json11::Json 都没有 ::Reader::Value 得到类似的东西,所以答案 2 也不起作用我稀释使用此 https://github.com/dropbox/json11 的 ppl 的答案是做这样的事情:

    ifstream ifile;
    int fsize;
    char * inBuf;
    ifile.open(file, ifstream::in);
    ifile.seekg(0, ios::end);
    fsize = (int)ifile.tellg();
    ifile.seekg(0, ios::beg);
    inBuf = new char[fsize];
    ifile.read(inBuf, fsize);
    string WINDOW_NAMES = string(inBuf);
    ifile.close();
    delete[] inBuf;
    Json my_json = Json::object { { "detectlist", WINDOW_NAMES } };
    while(looping == true) {
        for (auto s : Json::array(my_json)) {
            //code here.
        };
    };
    

    注意:这是一个循环,因为我希望它循环数据。 注意:这肯定会有一些错误,但至少我像上面那样正确打开了文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-18
      • 2016-10-25
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 2010-09-15
      相关资源
      最近更新 更多