如何将一个JSON文件读入C++字符串

11

我的代码像这样:

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文件的全部内容。

2
你需要打开文件,然后将其内容读入到一个 std::string 中。 - Hunter McMillen
4
应该使用 ifstream,而不是 istringstream。 - Kugel
2
使用 ifstream,而不是 istringstream - John Kugelman
4个回答

16

这个

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

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

这个

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

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

看到区别了吗?


4
我后来找到了一个好的解决方案。使用 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";
    }
}

10
我该如何在我的C++项目中使用Json::Reader - STF

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 文本写入字符串,它就可以正常工作……这是与文本格式有关吗? - Darkgaze

0

我尝试了上面的方法,但是它们在我的C++ 14中不起作用 :P 我得到了像从ifstream incomplete type is not allowed这样的东西,两个答案都是如此,并且2 json11::Json没有::Reader::Value,所以答案2也不起作用。我认为对于使用https://github.com/dropbox/json11的人来说,解决方法是像这样做:

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.
    };
};

注意:这是一个循环,因为我想要循环数据。 注意:这里可能会有一些错误,但至少我正确地打开了文件,不像上面。


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