2012-12-18 25 views
6

mio codice come questo:Come leggere un file JSON in stringa un C++

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

L'uscita è res/date.json, mentre quello che voglio veramente è l'intero contenuto di questo file JSON.

+2

È necessario aprire il file, quindi leggere il suo contenuto in un 'std :: string'. –

+4

Dovrebbe usare ifstream, non istringstream. – Kugel

+2

Usa 'ifstream', non' istringstream'. –

risposta

9

Questo

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

crea un flusso (denominato file) che legge dalla stringa "res/date.json".

Questo

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

crea un flusso (denominato file) che legge dal file di nome res/date.json.

Vedere la differenza?

3

Ho trovato una buona soluzione dopo. Utilizzo di parser in fstream.

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

Come posso avere 'Json :: Reader' nel mio progetto C++? – STF

0

ho provato la roba sopra, ma la cosa è che non funzionano in C++ 14 per me: P ottengo cose come da ifstream incomplete type is not allowed su entrambe le risposte e 2 json11 :: JSON non ha un ::Reader o un ::Value così risposta 2 non funziona o mi sottile l'answoer per ppl che usano questo https://github.com/dropbox/json11 è quello di fare qualcosa di simile:

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

Nota: cioè è in un ciclo come ho voluto che i dati ciclo. Nota: ci sono alcuni errori con questo, ma almeno ho aperto il file correttamente a differenza di sopra.