Tag TagDB::convertJsonToTag(string jsonString) { Tag itemReturn; Json::Value root; Json::Reader reader; bool parsedSuccess = reader.parse(jsonString, root, false); if (not parsedSuccess) { // Report failures and their locations in the document. cout << "Failed to parse JSON" << endl << reader.getFormatedErrorMessages() << endl; poco_error_f1(*logger, "convertJsonToTag: Failed to parse JSON %s", reader.getFormatedErrorMessages()); return itemReturn; } //Json::Value tagID = root["tagID"]; Json::Value tagName = root["tagName"]; Json::Value viewCounts = root["viewCounts"]; Json::Value dateAdd = root["dateAdd"]; Json::Value dateUpdate = root["dateUpdate"]; //itemReturn.tagID = tagID.asString(); itemReturn.tagName = tagName.asString(); itemReturn.viewCounts = viewCounts.asInt(); itemReturn.dateAdd = dateAdd.asString(); itemReturn.dateUpdate = dateUpdate.asString(); //poco_information(*logger, "convertJsonToTag: Convert from Json to Tag successfull"); return itemReturn; }
bool Ori::Read ( const std::string &camera_filename, int camera_id, const std::string &panoramic_filename, int panoramic_id ) { Json::Value camera; // will contains the camera root value after parsing. Json::Value panoramic; // will contains the panoramic root value after parsing. Json::Reader reader; std::ifstream camera_file(camera_filename.c_str(), std::ifstream::binary); if(!(camera_file.good() && reader.parse( camera_file, camera, false ))) { std::cerr << "Error reading " << camera_filename <<"\n"; std::cerr << reader.getFormatedErrorMessages() << "\n"; return false; } std::ifstream panoramic_file(panoramic_filename.c_str(), std::ifstream::binary); if(!(panoramic_file.good() && reader.parse( panoramic_file, panoramic, false ))) { std::cerr << "Error reading " << panoramic_filename <<"\n"; std::cerr << reader.getFormatedErrorMessages() << "\n"; return false; } double position[3]; double rotation[9]; int orientation; m_intrinsic = IntrinsicModel::New(camera[camera_id],position,rotation,orientation); return m_intrinsic!=NULL && m_extrinsic.Read(panoramic[panoramic_id],position,rotation,orientation); }
// SAVE LOAD JSON void UserStreamPlayer::setJson( const std::string &aPath ) { Json::Value *aJsonValue = new Json::Value(); Json::Reader reader; // Read the filestream std::ifstream filestream; // Load the file std::cout << "UserStreamPlayer::setJson - Attempting to load:" << aPath << std::endl; filestream.open( aPath.c_str(), std::ifstream::in); if( filestream == 0 ) { std::cout << "UserStreamPlayer::setJson - Failed to load file. Ignoring..." << std::endl; } // Parse the json file or retrieve errors bool parsingSuccessful = reader.parse( filestream, *aJsonValue ); if ( !parsingSuccessful ) { // report to the user the failure and their locations in the document. std::cout << "Failed to parse configuration\n" << reader.getFormatedErrorMessages() << std::endl; return; } parseJson ( aJsonValue ); }
static int parseAndSaveValueTree( const std::string &input, const std::string &actual, const std::string &kind, Json::Value &root ) { Json::Reader reader; bool parsingSuccessful = reader.parse( input, root ); if ( !parsingSuccessful ) { printf( "Failed to parse %s file: \n%s\n", kind.c_str(), reader.getFormatedErrorMessages().c_str() ); return 1; } FILE *factual = fopen( actual.c_str(), "wt" ); if ( !factual ) { printf( "Failed to create %s actual file.\n", kind.c_str() ); return 2; } printValueTree( factual, root ); fclose( factual ); return 0; }
std::string API::getExtraLink(const std::string& game_name, const std::string& id) { std::string url, link; url = this->config.get_extra_link + game_name + "/" + id + "/"; std::string json = this->getResponseOAuth(url); if (!json.empty()) { Json::Value root; Json::Reader *jsonparser = new Json::Reader; if (jsonparser->parse(json, root)) { #ifdef DEBUG std::cerr << "DEBUG INFO (API::getExtraLink)" << std::endl << root << std::endl; #endif int available = root["file"]["available"].isInt() ? root["file"]["available"].asInt() : std::stoi(root["file"]["available"].asString()); if (available) link = root["file"]["link"].asString(); } else { #ifdef DEBUG std::cerr << "DEBUG INFO (API::getExtraLink)" << std::endl << json << std::endl; #endif this->setError(jsonparser->getFormatedErrorMessages()); } delete jsonparser; } else { this->setError("Found nothing in " + url); } return link; }
bool TMQTTNinjaBridgeHandler::TryActivateBlock() { string url = "http://wakai.ninja.is/rest/v0/block/"; url += BlockId + "/activate"; std::ostringstream oss; CURLcode rc = GetHttpUrl(url, oss, 10); if(rc == CURLE_OK) { std::string html = oss.str(); cerr << "DEBUG: got response: " << html << endl; Json::Value root; Json::Reader reader; if(!reader.parse(html, root, false)) { cerr << "ERROR: Failed to parse Ninja activation response" << endl << reader.getFormatedErrorMessages() << endl; return false; } if (root.isMember("token")) { Token = root["token"].asString(); cout << "Got token: " << Token << endl; return true; } } //~ cerr << "rc: " << rc << endl; return false; }
int main(int argc, char *argv[]) { // ======= Classi ======= Simulator simulator; // Simulator OgreApp ogreapp(&simulator); // Ogre Application // ======= Leggi il file di configurazione ======= Json::Value conf; char config_file_name[512] = "config.conf\0"; if (argc > 1) { snprintf(config_file_name, sizeof(config_file_name), "%s", argv[1]); } else { usage(argv[0]); } printf("Leggo il file di configurazione '%s'...\n", config_file_name); std::ifstream config_file; config_file.open(config_file_name); Json::Reader reader; if ( !reader.parse( config_file, conf ) ) { // report to the user the failure and their locations in the document. error("Errore nel leggere il file di configurazione:\n%s", reader.getFormatedErrorMessages().c_str()); } config_file.close(); // ======= Applica la configurazione ======= simulator.load_configuration(conf); simulator.init_state(); ogreapp.load_configuration(conf); // ======= Start ======= ogreapp.startMainLoop(); return 0; }
/* example for favoorite info *** ParseFavoriteInfo {"status":"ok","songs":[ {"song_id":"1770088581", "album_id":"430596","name":"Kiss Kiss Kiss","style":null,"track":"1","artist_name":"\u90d1\u878d","artist_id":"2521", "lyric":"http:\/\/img.xiami.com\/.\/lyric\/upload\/81\/1770088581_1306767164.lrc", "inkui_url":"\/2521\/430596\/1770088581.mp3", "songwriters":null,"composer":null,"threads_count":"0","posts_count":"0", "listen_file":"\/2521\/430596\/01 1770088581_2098260.mp3","lyric_url":"0", "has_resource":null,"cd_serial":"1","sub_title":null,"complete":null,"singers":"\u90d1\u878d", "arrangement":null,"default_resource_id":"2098260","lyric_file":null,"title_url":"Kiss+Kiss+Kiss", "length":"212","recommends":"221","grade":"3", "title":"Kiss Kiss Kiss", "album_logo":"http:\/\/img.xiami.com\/.\/images\/album\/img21\/2521\/4305961300172212_2.jpg", "location":"http:\/\/f1.xiami.net\/2521\/430596\/01 1770088581_2098260.mp3","low_size":"2545371", "file_size":"6147852","low_hash":"9ecbd6391d246d68999549b6b4a60b0d","whole_hash":"00c291ff1735682ac3caa5b688f16382", "content_hash":"00c291ff1735682ac3caa5b688f16382","content_size":"6147852","category":"\u534e\u8bed","lock_lrc":"2","year_play":"45712"}, */ int DataManager::ParseFavoriteInfo(struct MemoryStruct *pJson) { //printf(" *** ParseFavoriteInfo %s\n", pJson->memory); Json::Reader reader; Json::Value root; bool ret; ret = reader.parse((const char*)pJson->memory, root); if (!ret) { // report to the user the failure and their locations in the document. std::cout << "Failed to parse configuration\n" << reader.getFormatedErrorMessages(); return 0; } bool isNull = root["status"].isNull(); if (isNull) { printf("get songs null\n"); return 0; } Json::Value songs; ret = false; ret=root.isMember("album"); if(ret) { Json::Value album = root["album"]; songs = album["songs"]; } else { songs = root["songs"]; } retSongNum = songs.size(); parse_songs(songs, MySongs, XIAMI_MY_SONGS_PAGE); return 1; }
int _tmain(int argc, _TCHAR* argv[]) { const int BufferLength = 1024; char readBuffer[BufferLength] = {0,}; if (false == ReadFromFile("test.json", readBuffer, BufferLength)) return 0; std::string config_doc = readBuffer; Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse( config_doc, root ); if ( !parsingSuccessful ) { std::cout << "Failed to parse configuration\n" << reader.getFormatedErrorMessages(); return 0; } std::string encoding = root.get("encoding", "" ).asString(); std::cout << encoding << std::endl; const Json::Value plugins = root["plug-ins"]; for ( int index = 0; index < plugins.size(); ++index ) { std::cout << plugins[index].asString() << std::endl; } std::cout << root["indent"].get("length", 0).asInt() << std::endl; std::cout << root["indent"]["use_space"].asBool() << std::endl; return 0; }
int DataManager::ParseSubBills(struct MemoryStruct *pJson) { Json::Reader reader; Json::Value root; bool ret; std::string name; //printf(" *** Line :%d ParseSubBills %s\n", __LINE__, pJson->memory); ret = reader.parse((const char*)pJson->memory, root); if (!ret) { std::cout << "Failed to parse configuration\n"<< reader.getFormatedErrorMessages(); return false; } bool isNull = root["status"].isNull(); if (isNull) { printf("get bills null\n"); return false; } Json::Value songs; std::string location; songs = root["songs"]; SongInfo *pSongs = BillSongList[0]; return parse_songs(songs, pSongs, XIAMI_BILL_SONG_NUM); }
Json::Value jsonParseFile(std::string filename) { std::fstream file(filename.c_str(), std::ios::in | std::ios::binary); if (!file.is_open()) { std::cout << "Error: could not open file " << filename << "\n"; return Json::Value(); } file.seekg(0, std::ios::end); int length = file.tellg(); file.seekg(0, std::ios::beg); char *buffer = new char[length + 1]; file.read(buffer, length); Json::Reader reader; Json::Value root; bool parsingSuccessful = reader.parse(buffer, root); if (parsingSuccessful) { return root; } else { std::cout << "In file " << filename << ": Parsing error(s):\n" << reader.getFormatedErrorMessages(); return Json::Value(); } }
int CCardFieldDlg::load_card_right_json() { int i,idx; Json::Value root; Json::Reader reader; std::ifstream input; //input.open("e:\\works\\cardlib\\ykt.v3_1.dev\\bin\\lcsmanager\\cardright.json"); input.open((LPCTSTR)m_jsonfile); if(input.is_open()==false) { AfxMessageBox("´ò¿ªÅäÖÃÎļþ´íÎó"); return -1; } if(reader.parse(input,root)==false) { std::string msg = "¶ÁÈ¡ÅäÖÃÎļþ´íÎó : " + reader.getFormatedErrorMessages(); AfxMessageBox(msg.c_str()); return -1; } std::string encoding = root.get("encoding","GBK").asString(); Json::Value fields = root["cardfield"]; Json::Value::Members fldid = fields.getMemberNames(); m_cardfield.clear(); for(i = 0;i < fldid.size();++i) { idx = atoi(fldid[i].c_str()); std::string v = fields.get(fldid[i],"Unknown").asString(); m_cardfield.insert(CARD_FILED_MAP::value_type(idx,v)); } if(fldid.size() > m_string_len) m_string_len = fldid.size(); // std::sort(m_cardfield.begin(),m_cardfield.end()); init_check_box(); return 0; }
void jsonParse() { ifstream jsonFile; jsonFile.open("/private/tmp/Ekho/search.json"); stringstream strStream; strStream << jsonFile.rdbuf(); string jsonString = strStream.str(); Json::Value root; Json::Reader reader; bool parseSuccess = reader.parse(jsonString, root, false); if (!parseSuccess) { printf("Failed to parse JSON file.\n"); cout << reader.getFormatedErrorMessages() << endl; return; } const Json::Value array = root["url"]; for (unsigned int index=0; index < array.size(); ++index) { cout << "Element " << index << " in array: " << array[index].asString() << endl; } const Json::Value notAnArray = root["not an array"]; if (!notAnArray.isNull()) { cout << "Not an array: " << notAnArray.asString() << endl; } cout << "Json pretty print: " << endl << root.toStyledString() << endl; return; }
int jsonParse(string _s) { // Let's parse it Json::Value root; Json::Reader reader; bool parsedSuccess = reader.parse(_s, root, false); if (not parsedSuccess) { // Report failures and their locations // in the document. cout << "Failed to parse JSON" << endl << reader.getFormatedErrorMessages() << endl; return 1; } Json::Value::Members mem = root.getMemberNames(); Json::Value child = root[mem[0]]; cout << "name: " << mem[0] << ", child: " << child.asString() << endl; for (int i = 1; i < mem.size(); ++i) { child = root[mem[i]]; cout << "name: " << mem[i] << endl; Json::Value::Members childMem = child.getMemberNames(); cout << "\t" << "type: " << child[childMem[0]].asString() << endl; cout << "\t" << "value: " << child[childMem[1]].asString() << endl; cout << "\t" << "typeGen: " << child[childMem[2]].asString() << endl; } return 1; }
void WriterConfig::readEditList(const std::string& filename, IsoMediaFile::Thumbs& thumbs) const { Json::Reader jsonReader; std::ifstream editListFile(filename); if (!editListFile.is_open()) { throw std::runtime_error("Unable to open input file '" + filename + "'"); } // Parse the editlist file Json::Value edit; bool parsingSuccess = jsonReader.parse(editListFile, edit, false); if (not parsingSuccess) { throw std::runtime_error("Failed to parse edit list file: " + jsonReader.getFormatedErrorMessages()); } thumbs.edit_list.numb_rept = std::stoi(edit["numb_rept"].asString()); for (unsigned int editIndex = 0; editIndex < edit["edit_unit"].size(); ++editIndex) { IsoMediaFile::EditUnit newEditUnit; newEditUnit.edit_type = edit["edit_unit"][editIndex]["edit_type"].asString(); newEditUnit.mdia_time = std::stoi(edit["edit_unit"][editIndex]["mdia_time"].asString()); newEditUnit.time_span = std::stoi(edit["edit_unit"][editIndex]["time_span"].asString()); thumbs.edit_list.edit_unit.push_back(newEditUnit); } }
////////////////////////////////////////////////////////////////////////// // loadJsonFile BcBool CsPackageImporter::loadJsonFile( const BcChar* pFileName, Json::Value& Root ) { BcBool Success = BcFalse; BcFile File; if( File.open( pFileName ) ) { const BcU8* pData = File.readAllBytes(); Json::Reader Reader; if( Reader.parse( (const char*)pData, (const char*)pData + File.size(), Root ) ) { Success = BcTrue; } else { PSY_LOG( "Failed to parse Json:\n %s\n", Reader.getFormatedErrorMessages().c_str() ); BcAssertMsg( BcFalse, "Failed to parse \"%s\", see log for more details.", pFileName ); } BcMemFree( (void*)pData ); } else { BcAssertMsg( BcFalse, "Failed to load \"%s\"", pFileName ); } return Success; }
// virtual bool LLGoogleTranslationHandler::parseResponse( int& status, const std::string& body, std::string& translation, std::string& detected_lang, std::string& err_msg) const { Json::Value root; Json::Reader reader; if (!reader.parse(body, root)) { err_msg = reader.getFormatedErrorMessages(); return false; } if (!root.isObject()) // empty response? should not happen { return false; } if (status != STATUS_OK) { // Request failed. Extract error message from the response. parseErrorResponse(root, status, err_msg); return false; } // Request succeeded, extract translation from the response. return parseTranslation(root, translation, detected_lang); }
void EpgStore::FromJson(std::string strJson, EpgProgramInfo& epgInfo) { if (strJson.length() == 0) { return; } Json::Value json; Json::Reader reader; if (!reader.parse(strJson, json)) { CLog::Log(LOGERROR, "Error parsing json: %s", reader.getFormatedErrorMessages().c_str()); return; } epgInfo.title = json["title"].asString(); epgInfo.synopsis = json["synopsis"].asString(); epgInfo.rating = json["rating"].asString(); epgInfo.origAirDate = json["orig_airdate"].asString(); epgInfo.seasonNumber = json["season_num"].asString(); epgInfo.episodeNumber = json["episode_num"].asString(); epgInfo.thumb = json["thumb"].asString(); epgInfo.showRunNumber = json["show_num"].asString(); epgInfo.episodeTitle = json["episode_title"].asString(); epgInfo.isNew = json["new"].asBool(); }
TEST(jsoncpp, path_list) { std::stringstream ss; ss << getExampleJson(); Json::Value root; Json::Reader reader; //printf("parse, \n%s\n", ss.str().c_str()); bool parsingSuccessful = reader.parse(ss, root); if(!parsingSuccessful) { printf("Failed to parse, %s\n", reader.getFormatedErrorMessages().c_str()); } ASSERT_EQ(parsingSuccessful, true); Json::Path p("plug-ins"); Json::Value v = p.resolve(root); ASSERT_EQ(v.size(), 3); Json::Path p2("plug-ins_xx"); v = p2.resolve(root); ASSERT_EQ(true, v.isNull()); Json::Path p3("plug-ins_xx"); v = p3.resolve(root, "[]"); ASSERT_FALSE(v.isNull()); ASSERT_EQ(0, v.size()); }
TEST(jsoncpp, path_parse) { std::stringstream ss; ss << getExampleJson(); Json::Value root; Json::Reader reader; //printf("parse, \n%s\n", ss.str().c_str()); bool parsingSuccessful = reader.parse(ss, root); if(!parsingSuccessful) { printf("Failed to parse, %s\n", reader.getFormatedErrorMessages().c_str()); } ASSERT_EQ(parsingSuccessful, true); Json::Path p("indent.length"); Json::Value v = p.resolve(root); ASSERT_EQ(v.asInt(), 3); Json::Path p2("indent.length_xx"); v = p2.resolve(root); EXPECT_EQ(true, v.isNull()); Json::Path p3("indent.length_xx.yy"); v = p3.resolve(root); EXPECT_EQ(true, v.isNull()); }
bool parseRateJson(const char* str_json) { if (!str_json){ G_LOG_FC(LOG_ERROR, "parseRateJson str_json null"); return false; } Json::Reader reader; Json::Value root; if (!reader.parse(str_json, root)){ std::string err = reader.getFormatedErrorMessages(); G_LOG_FC(LOG_ERROR, "read rate err:%s json:%s", err.c_str(), str_json); return false; } float fAsk = 0.0f; float fBid = 0.0f; float fRate = 0.0f; try { Json::Value rate_json = root["query"]["results"]["rate"]; fAsk = atof(rate_json["Ask"].asString().c_str()); fBid = atof(rate_json["Bid"].asString().c_str()); fRate = atof(rate_json["Rate"].asString().c_str()); UserConfigGen::instance()->setFloat("exchange_ask", fAsk); UserConfigGen::instance()->setFloat("exchange_bid", fBid); UserConfigGen::instance()->setFloat("exchange_rate", fRate); UserConfigGen::instance()->setString("exchange_date", rate_json["Date"].asString()); } catch (...) { G_LOG_FC(LOG_ERROR, "read rate catchs ask:%f bid:%f rate:%f", fAsk, fBid, fRate); } return true; }
void FeatureTestHandler::saveDataToModel(){ Json::Value *vec = DataToJson(); Json::Value oldroot; getModelFile()->seekg(0, getModelFile()->beg); Json::Reader reader; if(fs::is_empty(path_)) { cout << "Empty model file." << endl; } else { bool parsingSuccessful = reader.parse( (*getModelFile()), oldroot, false ); if(oldroot.size() == 0 || oldroot[MODEL_ROOT_].isNull()) { cerr << "File not empty, but no model found" << endl; } else if ( !parsingSuccessful ) { cerr <<"Parsing error :" <<reader.getFormatedErrorMessages() << endl; return; } } getModelFile()->clear(); //Take the feature section of the model oldroot[MODEL_ROOT_][getFeatureName()] = *vec; getModelFile()->seekg(0, getModelFile()->beg); (*getModelFile()) << oldroot; delete vec; return; }
bool File::readInto(Json::Value &root, bool keepComments) const { if(!exists()) { Ogre::String msg = "could not open :" + fullPath() + ": file not found."; if(Debug::isInit) Debug::error(STEEL_METH_INTRO, msg).endl(); else std::cerr << STEEL_METH_INTRO.c_str() << msg.c_str() << std::endl; return false; } Json::Reader reader; Ogre::String content = read(false); root.clear(); if(!reader.parse(content, root, keepComments)) { Ogre::String msg = "Could not parse content:" + reader.getFormatedErrorMessages() + "\non :" + content; if(Debug::isInit) Debug::error(STEEL_METH_INTRO, msg).endl(); else std::cerr << STEEL_METH_INTRO.c_str() << msg.c_str() << std::endl; return false; } return true; }
BOOL CLoginDlg::getToken(char* readBuffer) { BOOL bRtn = TRUE; std::string config_doc = readBuffer; Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse(config_doc, root); if (!parsingSuccessful) { std::cout << "Failed to parse configuration\n" << reader.getFormatedErrorMessages(); bRtn = FALSE; return bRtn; } //array CComm func; const Json::Value array = root["data"]; for (unsigned int i = 0; i < array.size(); ++i) { std::string item = array[i].get("token", "default").asString(); if (item != "default"){ //m_strToken = (LPCTSTR)item.c_str(); m_strMyToken = item.c_str(); //토큰 저장. WritePrivateProfileString(L"MYINFO", L"token", m_strMyToken, func.m_strINI); TRACE("\r\ntoken=%s\r\n", m_strMyToken); break; } } return bRtn; }
////////////////////////////////////////////////////////////////////////// // parseJsonFile BcBool CsCore::parseJsonFile( const BcChar* pFileName, Json::Value& Root ) { BcBool Success = BcFalse; BcFile File; if( File.open( pFileName ) ) { char* pData = new char[ File.size() ]; File.read( pData, File.size() ); Json::Reader Reader; if( Reader.parse( pData, pData + File.size(), Root ) ) { Success = BcTrue; // Add file for monitoring. FsCore::pImpl()->addFileMonitor( pFileName ); } else { BcPrintf( "CsCore: Failed to parse Json:\n %s\n", Reader.getFormatedErrorMessages().c_str() ); } delete [] pData; } return Success; }
int main(int argc, char **argv) { ifstream file("data.json"); // Let's parse it Json::Value root; Json::Reader reader; bool parsedSuccess = reader.parse(file, root, false); if(not parsedSuccess) { cout << "Failed to parse JSON" << endl << reader.getFormatedErrorMessages() << endl; return 1; } const Json::Value array = root["characterData"]; //const Json::Value servlets = root["characterData"]["1"]["base_str"]; //const Json::Value characters = root["characterData"]["1"]; //cout << servlets.asInt(); for(unsigned int index = 0; index < array.size(); index++) { string s = boost::lexical_cast<string>(index + 1); //const Json::Value str = root["characterData"][s]["base_str"]; const Json::Value str = array[s]["base_str"]; cout << str.asInt() << endl; const Json::Value dex = array[s]["base_dex"]; //const Json::Value dex = root["characterData"][s]["base_dex"]; cout << dex.asInt() << endl; const Json::Value intel = array[s]["base_int"]; //const Json::Value intel = root["characterData"][s]["base_int"]; cout << intel.asInt() << endl; cout << endl; //cout << "Element " << index << " in array: " << array[index].asString() << endl; //Json::Value temp = array.get("base_dex", temp); //cout << temp.asString() << endl; //std::cout << servlets[index].asString() << std::endl; //cout << "element " << characters[index].asString() << endl; } Json::Value array2 = root["root"]; for(unsigned int index = 0; index < array2.size() - 1; index++) { cout << array2["out"][index].asInt() << endl; } /* // If we want to print JSON is as easy as doing: cout << "Json Example pretty print: " << endl << root.toStyledString() << endl; */ return 0; }
bool ContactList::loadContacts(string& error) { // Create file if it does not exist if (!fexists(fileName.c_str())) { ofstream out(fileName); out << "[]" << endl; out.close(); if (out.fail() || out.bad()) { stringstream ss; ss << "File " << fileName << " did not exist and could not create: " << strerror(errno); error = ss.str(); return false; } } ifstream in(fileName); string jsonText((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); in.close(); if (in.fail() || in.bad()) { stringstream ss; ss << "Could not read " << fileName << ": " << strerror(errno); error = ss.str(); return false; } Json::Reader reader; Json::Value doc; if (!reader.parse(jsonText, doc)) { error = "Could not parse " + fileName + ": " + reader.getFormatedErrorMessages(); return false; } if (!doc.isArray()) { error = "JSON document is not an array"; return false; } int n = doc.size(); for (int i = 0; i < n; ++i) { Json::Value& personJson = doc[i]; Person p; if (!p.fromJson(personJson, error)) { return false; } string personValidationError; if (!p.isValid(personValidationError)) { error = "Invalid contact record " + personJson.toStyledString() + ": " + personValidationError; return false; } addContact(p); } error.clear(); return true; }
int rename_file(Cli_Info cli) { // Will need to parse object as json file, get the "filename" string and pass it in as an arg. Json::Value root; Json::Value vec(Json::arrayValue); Json::Reader reader; std::ifstream test(cli.uid, std::ifstream::binary); bool Parsed = reader.parse(test, root, false); if(!Parsed){ // Throw out an error to say that the document has not been parsed correctly. std::cout << reader.getFormatedErrorMessages() << "\n"; errorCount++; remove(cli.uid); return 0;} vec.append(Json::Value(1)); if (cli.ctype == OSX) root["Time from OSX"] = cli.duration; else if (cli.ctype == ANDROID) root["Time from ANDROID"] = cli.duration; std::string filename = root.get("filename", "tmp.json").asString(); std::string ext = root.get("extension", "tmp.json").asString(); std::ofstream f; f.open(cli.uid); f << root.toStyledString(); f.close(); bool success = false; char str[30]; int count = 1; sprintf(str, "%s.%s", filename.c_str(), ext.c_str()); std::string fname = std::string(str); if (boost::filesystem::exists(fname.c_str())) { printf("File Exists\n"); do { sprintf(str, "%s - %d.%s", filename.c_str(),count, ext.c_str()); fname = std::string(str); if (boost::filesystem::exists(fname.c_str())) count++; // File was found, increment counter else { rename(cli.uid, str); success = true; } }while (success == false); } else rename(cli.uid, str); return 1; }
eventController::eventController(std::string eventlist, Engine* eng, std::map< std::string, variant<paraVarType> >& m) : genericContorller(eng), varMap(m), userInputRequired(0) { std::string in = get_file_contents(eventlist.c_str()); Json::Value root; Json::Reader reader; if (reader.parse( in, root )){ event_count = root.get("Count", 0 ).asInt(); for(unsigned int i = 0; i < event_count; i++){ std::string in2 = get_file_contents(root["Path"][i].asCString()); Json::Value root2; Json::Reader reader2; if (reader.parse( in2, root2 )){ event trigger; trigger.stk.resize(root2["Command"].size()); for(unsigned int i = 0; i < root2["Command"].size(); i++){ trigger.stk[i] = root2["Command"][i].asString(); } trigger.trigBy = root2["Name"].asString(); trigger.triggerType = root2["triggerType"].asInt(); trigger.pc = 0; event_list.insert (event_list.begin(), std::pair<std::string, event>(trigger.trigBy, trigger)); }else{ std::cout << "Failed to parse configuration\n" << reader.getFormatedErrorMessages(); exit(128); } } }else{ std::cout << "Failed to parse configuration\n" << reader.getFormatedErrorMessages(); exit(128); } }
Json::Value getJsonFileRoot(string mFilePath) { Json::Value root; Json::Reader reader; ifstream stream(mFilePath, std::ifstream::binary); bool parsingSuccessful = reader.parse( stream, root, false ); if (!parsingSuccessful) cout << reader.getFormatedErrorMessages() << endl; return root; }