2012-12-18 84 views
6

我这样的代码:如何阅读JSON文件到C++字符串

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'。 –

+4

应该使用ifstream,而不是istringstream。 – Kugel

+2

使用'ifstream',而不是'istringstream'。 –

回答

9

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

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

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

创建流(名为file)从命名res/date.json读取文件。

看到区别?

3

我后来发现了一个很好的解决方案。在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"; 
    } 
} 
+8

如何在我的C++项目中使用'Json :: Reader'? – STF

0

我试过的东西上面,但事情是他们不工作,在C++ 14,我:P 我得到的东西就像从ifstream的incomplete type is not allowed两个答案和2 json11 :: JSON没有有::Reader::Value所以答案2不工作,要么我的answoer薄谁使用这个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. 
    }; 
}; 

注:即是在一个循环中,因为我想它循环的数据。 注意:这肯定会出现一些错误,但至少我正确地打开了与上面不同的文件。