2015-06-29 8 views

risposta

19

Ciao E 'abbastanza semplice:

1 - Hai bisogno di un oggetto di valore CPP JSON (JSON :: Value) per memorizzare i dati

2 - Utilizzare un JSON Reader (JSON :: Reader) per leggere una stringa JSON e analizzare in un JSON oggetto

3 - Fate il vostro roba :)

Ecco un semplice codice per fare quei passi:

#include <stdio.h> 
#include <jsoncpp/json/json.h> 
#include <jsoncpp/json/reader.h> 
#include <jsoncpp/json/writer.h> 
#include <jsoncpp/json/value.h> 
#include <string> 

int main(int argc, const char* argv[]) 
{ 

    std::string strJson = "{\"mykey\" : \"myvalue\"}"; // need escape the quotes 

    Json::Value root; 
    Json::Reader reader; 
    bool parsingSuccessful = reader.parse(strJson.c_str(), root);  //parse process 
    if (!parsingSuccessful) 
    { 
     std::cout << "Failed to parse" 
       << reader.getFormattedErrorMessages(); 
     return 0; 
    } 
    std::cout << root.get("mykey", "A Default Value if not exists").asString() << std::endl; 
    return 0; 
} 

da compilare: g ++ -o YourMainFile.cpp principale jsoncpp -l

Spero che aiuta;)

+0

Wow, questo è stato il miglior innesco rapido su C++ e JSON che ho visto. stupendo –

+0

Grazie, amore per risparmiare tempo. – nenchev

+2

Con stringa raw (C++ 11), puoi usare 'strJson = R" ({"mykey": "myvalue"}) ";'. – Jarod42