void Com::JsonParseOrder(Order_t* order){ Json::Value root; // will contains the root value after parsing. Json::Reader reader; bool parsingSuccessful = reader.parse( buffer, root ); if ( !parsingSuccessful ) { std::cout << "Failed to parse configuration\n" << reader.getFormattedErrorMessages(); return; } order->orderId = root["order_id"].asInt(); for( Json::ValueIterator itr = root["recipe"].begin() ; itr != root["recipe"].end() ; itr++ ) { #ifdef DEBUG std::cout << itr.key().asString() << " " << *itr; #endif order->ingredients.push_back(makeIngredientItem(itr.key().asString(), (*itr).asInt())); } #ifdef DEBUG printf("parsing passed\n"); #endif }
std::map<std::string, std::string> jsonValueToAccount(Json::Value& value, const std::string& accountId) { auto idPath_ = fileutils::get_data_dir() + DIR_SEPARATOR_STR + accountId; fileutils::check_dir(idPath_.c_str(), 0700); auto detailsMap = DRing::getAccountTemplate(value[DRing::Account::ConfProperties::TYPE].asString()); for( Json::ValueIterator itr = value.begin() ; itr != value.end() ; itr++ ) { if (itr->asString().empty()) continue; if (itr.key().asString().compare(DRing::Account::ConfProperties::TLS::CA_LIST_FILE) == 0) { std::string fileContent(itr->asString()); fileutils::saveFile(idPath_ + DIR_SEPARATOR_STR "ca.key", {fileContent.begin(), fileContent.end()}, 0600); } else if (itr.key().asString().compare(DRing::Account::ConfProperties::TLS::PRIVATE_KEY_FILE) == 0) { std::string fileContent(itr->asString()); fileutils::saveFile(idPath_ + DIR_SEPARATOR_STR "dht.key", {fileContent.begin(), fileContent.end()}, 0600); } else if (itr.key().asString().compare(DRing::Account::ConfProperties::TLS::CERTIFICATE_FILE) == 0) { std::string fileContent(itr->asString()); fileutils::saveFile(idPath_ + DIR_SEPARATOR_STR "dht.crt", {fileContent.begin(), fileContent.end()}, 0600); } else detailsMap[itr.key().asString()] = itr->asString(); } return detailsMap; }
void JsonParser::parseMaterials(Json::Value &root){ LOG_DEBUG("Parsing Materials."); bool foundMaterials = false; for( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) { std::string key = itr.key().asString(); if (key == "materials") { foundMaterials = true; // loop through materials Json::Value objRoot = *itr; for( Json::ValueIterator objItr = objRoot.begin() ; objItr != objRoot.end() ; objItr++ ) { std::string matName = objItr.key().asString(); LOG_DEBUG("Found material: " << matName); // we first check if we're dealing with a light or mesh std::string matType = getStringAttr("type", *objItr); Material * mat = getMaterial(matType, matName, *objItr, renderEnv); // add to shading engine renderEnv->shadingEngine->registerMaterial(matName, mat); } LOG_DEBUG("Done parsing materials.\n"); break; } } if (!foundMaterials) { LOG_WARNING("No materials found in file " << filename << "."); } }
bool CannyReader::readFromFile() { Timer aTimer; std::ifstream cannyFile(srcFile); cannyFile.precision(20); if (cannyFile.is_open()) { std::stringstream buffer; buffer << cannyFile.rdbuf(); std::string contents(buffer.str()); cout << "Time to Read: " << aTimer.elapsed() << endl; aTimer.restart(); Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse( contents, root ); cout << "Time to parse: " << aTimer.elapsed() << endl; aTimer.restart(); if (parsingSuccessful) { for( Json::ValueIterator outer = root.begin() ; outer != root.end() ; outer++ ) { int camNum = outer.key().asInt(); Json::Value oneCam = root[camNum]; for( Json::ValueIterator itr = oneCam.begin() ; itr != oneCam.end() ; itr++ ) { vector<Line_Segment *>* lineSegments = new vector<Line_Segment *>(); int key = atoi(itr.key().asCString()); Json::Value jsonSegments = oneCam[itr.key().asCString()]; for( Json::ValueIterator itr2 = jsonSegments.begin() ; itr2 != jsonSegments.end() ; itr2++ ) { Json::Value jsonSeg = jsonSegments[itr2.key().asInt()]; Line_Segment* seg = (Line_Segment *) malloc(sizeof(Line_Segment)); seg->row1 = jsonSeg["r1"].asInt(); seg->col1 = jsonSeg["c1"].asInt(); seg->row2 = jsonSeg["r2"].asInt(); seg->col2 = jsonSeg["c2"].asInt(); lineSegments->push_back(seg); } precomputedCannySegments[camNum][key] = lineSegments; } } cannyFile.close(); cout << "Time to reconstruct: " << aTimer.elapsed() << endl; return true; } else { return false; } } return false; }
Translator::Langs Translator::getLangs() const { _curlBuffer = ""; Translator::Langs langs; std::string mylang = getMyLang(); if(mylang.empty()) mylang = "en"; // default std::string url = "https://translate.yandex.net/api/v1.5/tr.json/getLangs?key="; url += getApiKey(); url += "&ui="; url += mylang; curl_easy_setopt(curl, CURLOPT_URL, url.c_str());; CURLcode res = curl_easy_perform(curl); if(res != CURLE_OK) { // error } Json::Reader reader; Json::Value root; reader.parse(_curlBuffer, root); for(Json::ValueIterator it = root["langs"].begin(); it != root["langs"].end(); it++) { langs.push_back(std::make_pair( it.key().asString(), // key (*it).asString() // value )); } return langs; }
Objects::Object::Object(Json::Value data) : self_data( data ), self_x(0), self_y(0), self_w(0), self_h(0) { Json::Value dimensions = data["dimensions"]; if ( dimensions.isObject() ) { // Coordinates are stored as doubles, but interpretted as either // pixel coordinates or fractional. If ANY dimension is a double, then // they all should be (why would you use a double coordinate otherwise?) self_coordType = Objects::NON_NORM; for ( Json::ValueIterator itr = dimensions.begin(); itr != dimensions.end(); itr ++ ) { string key = itr.key().asString(); if (dimensions[ key ] . isDouble() ) { self_coordType = Objects::NORM; break; } } self_x = dimensions["x"].asDouble(); self_y = dimensions["y"].asDouble(); } }
void JsonParser::parseCamera(Json::Value &root){ LOG_DEBUG("Parsing Camera."); bool foundCamera = false; // Options for( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) { std::string key = itr.key().asString(); if (key == "renderCam") { foundCamera = true; // read all standard data double r_fieldOfView = getDoubleAttr("fov", *itr); Transform r_transform = getTransformAttr("transforms", *itr); // TODO: check for any ones we've skipped and warn the user // TODO: handle errors gracefully // apply read data (*renderEnv->globals)[FieldOfView] = r_fieldOfView; cameraTransform = new Transform(r_transform); LOG_DEBUG("Done parsing Camera.\n"); break; } } if (!foundCamera) { LOG_WARNING("No render camera found in file " << filename << "."); } }
/** * Read a map of {list_name : class_list} from json */ std::unordered_map<std::string, std::vector<std::string> > ConfigFiles::load_class_lists() { std::unordered_map<std::string, std::vector<std::string> > lists; std::string class_lists_filename; this->m_json.get("class_lists", "", class_lists_filename); if (class_lists_filename.empty()) { return lists; } std::ifstream input(class_lists_filename); Json::Reader reader; Json::Value root; bool parsing_succeeded = reader.parse(input, root); always_assert_log(parsing_succeeded, "Failed to parse class list json from file: %s\n%s", class_lists_filename.c_str(), reader.getFormattedErrorMessages().c_str()); for (Json::ValueIterator it = root.begin(); it != root.end(); ++it) { std::vector<std::string> class_list; Json::Value current_list = *it; for (Json::ValueIterator list_it = current_list.begin(); list_it != current_list.end(); ++list_it) { lists[it.key().asString()].push_back((*list_it).asString()); } } lists["secondary_dex_head.list"] = get_coldstart_classes(); return lists; }
string HandlerChat::readChat(string chatString,string user,string messageId,string conversationId){ /**Leo la CANT_MENSAJES desde mensajeId del chat desde la vista del usuario.Actualiza los estados con los * ultimos mensajes leidos en la conversacion.**/ Json::Value chat=jsonParse.stringToValue(chatString); Json::Value lastsMessages; Json::Value lastsMessagesMsg= Json::Value(Json::arrayValue); LOG(DEBUG)<<chatString; int lastMessageRead; int lastMessageId=chat["message_id"].asInt(); if(chat["User1"].asString()==user){ lastMessageRead=chat["LastMessage2"].asInt(); chat["LastMessage1"]=0; }else{ lastMessageRead=chat["LastMessage1"].asInt(); chat["LastMessage2"]=0; } Json::Value messages=chat["Messages"]; int messageIdSearch=atoi(messageId.c_str()); for( Json::ValueIterator itr = messages.begin() ; itr != messages.end() ; itr++ ){ LOG(INFO)<<"id "<<itr.key().asString(); int currentMessageId=atoi(itr.key().asString().c_str()); int min=messageIdSearch-CANT_MESSAGES; if((currentMessageId<=messageIdSearch)&&(currentMessageId>=(min))){ Json::Value Message=*itr; if(currentMessageId>=(lastMessageId-lastMessageRead)){ Message["status"]="D"; }else{ Message["status"]="R"; } Message["message_id"]=itr.key().asString(); lastsMessagesMsg.append(Message); } } lastsMessages["messages"]=lastsMessagesMsg; int bottomMessageId=messageIdSearch-CANT_MESSAGES; if(bottomMessageId<0){ bottomMessageId=0; } lastsMessages["LastMessageId"]=bottomMessageId; string lastsMessagesString=this->jsonParse.valueToString(lastsMessages); chatString=this->jsonParse.valueToString(chat); LOG(DEBUG)<<chatString; DBtuple putChat("chat_"+conversationId,chatString); DB->put(putChat); return lastsMessagesString; }
qpid::types::Variant::Map agocontrol::jsonToVariantMap(Json::Value value) { Variant::Map map; try { for (Json::ValueIterator it = value.begin(); it != value.end(); it++) { // printf("%s\n",it.key().asString().c_str()); // printf("%s\n", (*it).asString().c_str()); if ((*it).size() > 0) { // cout << "JSON Type: " << (*it).type() << endl; // cout << "Key: " << it.key().asString() << endl; if ((*it).type() == 6) { map[it.key().asString()] = jsonToVariantList((*it)); } else if ((*it).type() == 7) { map[it.key().asString()] = jsonToVariantMap((*it)); } } else { if ((*it).isString()) map[it.key().asString()] = (*it).asString(); if ((*it).isBool()) map[it.key().asString()] = (*it).asBool(); if ((*it).isInt()) map[it.key().asString()] = (*it).asInt(); if ((*it).isUInt()) map[it.key().asString()] = (*it).asUInt(); if ((*it).isDouble()) map[it.key().asString()] = (*it).asDouble(); } } } catch (const std::exception& error) { cout << "ERROR! Exception during JSON->Variant::Map conversion!" << endl; stringstream errorstring; errorstring << error.what(); cout << "EXCEPTION: " << errorstring.str() << endl; } return map; }
void ItemEquipper::deserializeEquippedItems(Json::Value& root) { Item* item; for (Json::ValueIterator it = root.begin(); it != root.end(); it++) { item = new Item(); item->deserialize(*it); _equippedItems[it.key().asInt()] = item; } }
void JsonParser::parseGeometry(Json::Value &root){ LOG_DEBUG("Parsing Geometry."); bool foundGeometry = false; for( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) { std::string key = itr.key().asString(); if (key == "objects") { foundGeometry = true; // find object Json::Value objRoot = *itr; for( Json::ValueIterator objItr = objRoot.begin() ; objItr != objRoot.end() ; objItr++ ) { LOG_DEBUG("Found object: " << objItr.key().asString()); // check if we're dealing with a light or mesh std::string objType = getStringAttr("type", *objItr); if (objType == "geometry"){ std::tr1::shared_ptr<AuroraObject> geo = getGeometry(*cameraTransform, *objItr, renderEnv); objects.push_back(geo); } else if (objType == "light"){ Light* light = getLight(*cameraTransform, *objItr, (*renderEnv->globals)[LightSamples], renderEnv); lights.push_back(light); } else if (objType == "envlight"){ Light* light = getEnvLight(*cameraTransform, *objItr, (*renderEnv->globals)[LightSamples], renderEnv); lights.push_back(light); } else { LOG_WARNING("Unknown object type found: " << objType); } } // apply to globals LOG_DEBUG("Done parsing Geometry.\n"); break; } } if (!foundGeometry) { LOG_WARNING("No geometry found in file " << filename << "."); } }
string HandlerChat::getChatId(string remitente,string destinatario){ /**Busca el chat id de la conversacion sino existe lo crea.**/ Json::Value chatsId=getChatsIdValueFromDestinatario(destinatario); string id=""; for( Json::ValueIterator itr = chatsId.begin() ; itr != chatsId.end() ; itr++ ){ if((*itr).asString()==remitente){ id=itr.key().asString(); } } return id; }
std::list<std::string> CJSONHandler::ParseAvailLanguagesTX(std::string strJSON, bool bIsXBMCCore, std::string strURL) { Json::Value root; // will contains the root value after parsing. Json::Reader reader; std::string lang; std::list<std::string> listLangs; bool parsingSuccessful = reader.parse(strJSON, root ); if ( !parsingSuccessful ) { CLog::Log(logERROR, "CJSONHandler::ParseAvailLanguagesTX: no valid JSON data"); return listLangs; } const Json::Value langs = root; std::string strLangsToFetch; std::string strLangsToDrop; std::string strLangsBlacklisted; for(Json::ValueIterator itr = langs.begin() ; itr != langs.end() ; itr++) { lang = itr.key().asString(); if (lang == "unknown") CLog::Log(logERROR, "JSONHandler: ParseLangs: no language code in json data. json string:\n %s", strJSON.c_str()); Json::Value valu = *itr; std::string strCompletedPerc = valu.get("completed", "unknown").asString(); std::string strModTime = valu.get("last_update", "unknown").asString(); bool bLangBlacklisted = g_LCodeHandler.CheckIfLangCodeBlacklisted(lang); // we only add language codes to the list which has a minimum ready percentage defined in the xml file // we make an exception with all English derived languages, as they can have only a few srings changed if (lang.find("en_") != std::string::npos || strtol(&strCompletedPerc[0], NULL, 10) > g_Settings.GetMinCompletion()-1 || !bIsXBMCCore) { if (!bLangBlacklisted) { strLangsToFetch += lang + ": " + strCompletedPerc + ", "; listLangs.push_back(lang); g_Fileversion.SetVersionForURL(strURL + "translation/" + lang + "/?file", strModTime); } else { strLangsBlacklisted += lang + ": " + strCompletedPerc + ", "; } } else strLangsToDrop += lang + ": " + strCompletedPerc + ", "; }; CLog::Log(logINFO, "JSONHandler: ParseAvailLangs: Languages to be Fetcehed: %s", strLangsToFetch.c_str()); CLog::Log(logINFO, "JSONHandler: ParseAvailLangs: Languages to be Dropped (not enough completion): %s", strLangsToDrop.c_str()); CLog::Log(logINFO, "JSONHandler: ParseAvailLangs: Languages to be Dropped due they are blacklisted: %s",strLangsBlacklisted.c_str()); return listLangs; };
void BuyedListRequestData::decode_from_json_object(const Json::Value &root) { Json::Value tmp; if ( root.isObject() && root.isMember("total") ) { tmp = root["total"]; if ( !tmp.isNull() ) { total = tmp.asString(); } } if ( root.isObject() && root.isMember("contentUuid") ) { const Json::Value map_contentUuid = root["contentUuid"]; if ( !map_contentUuid.isNull() ) { for( Json::ValueIterator it = map_contentUuid.begin(); it != map_contentUuid.end(); ++it ) { std::string key = it.key().asString(); contentUuid[key] = map_contentUuid[key].asString(); } } } if ( root.isObject() && root.isMember("buyCount") ) { const Json::Value map_buyCount = root["buyCount"]; if ( !map_buyCount.isNull() ) { for( Json::ValueIterator it = map_buyCount.begin(); it != map_buyCount.end(); ++it ) { std::string key = it.key().asString(); buyCount[key] = map_buyCount[key].asInt(); } } } }
void ofApp::record(){ ofFile newfile(ofToDataPath("coordinates.json"), ofFile::WriteOnly); string time = ofToString(ofGetElapsedTimef()); for(Json::ValueIterator i = untimedData.begin() ; i != untimedData.end(); i++) { string id = i.key().asString(); data[id][time]["position"] = untimedData[id]["position"]; data[ofToString(id)][time]["rotation"] = untimedData[id]["rotation"]; cout << data; } if (data != ofxJSONElement::null) newfile << data; sound.play(); }
void ResourceManager::loadResources() { Json::Value models = ParamReader::get()->getParam("resources.models"); Json::Value textures = ParamReader::get()->getParam("resources.textures"); Json::Value shaders = ParamReader::get()->getParam("resources.shaders"); Json::Value dfdescs = ParamReader::get()->getParam("resources.depthFields"); for (Json::ValueIterator texture = textures.begin(); texture != textures.end(); texture++) { textures_[texture.key().asString()] = makeTexture((*texture).asString()); } LOG(DEBUG) << "Loading models\n"; for (Json::ValueIterator it = models.begin(); it != models.end(); it++) { std::string model_name = it.key().asString(); Json::Value model_desc = *it; std::string model_file = must_have_idx(model_desc, "file").asString(); LOG(DEBUG) << "loading " << model_file << '\n'; auto *model = loadModel(model_file); setModelTransform(model, getModelTransform(model_desc)); models_[model_name] = model; } for (Json::ValueIterator shader = shaders.begin(); shader != shaders.end(); shader++) { GLuint program = loadProgram((*shader)["vert"].asString(), (*shader)["frag"].asString()); shaders_[shader.key().asString()] = new Shader(program); } for (Json::ValueIterator dfdesc = dfdescs.begin(); dfdesc != dfdescs.end(); dfdesc++) { DepthField *df = new DepthField; df->texture = makeTexture((*dfdesc)["file"].asString()); df->minDist = (*dfdesc)["minDist"].asFloat(); df->maxDist = (*dfdesc)["maxDist"].asFloat(); depthFields_[dfdesc.key().asString()] = df; } }
void JsonParser::parseShaders(Json::Value &root){ LOG_DEBUG("Parsing Shaders."); bool foundShaders = false; for( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) { std::string key = itr.key().asString(); if (key == "shaders") { foundShaders = true; // loop through shaders Json::Value objRoot = *itr; for( Json::ValueIterator objItr = objRoot.begin() ; objItr != objRoot.end() ; objItr++ ) { std::string shdName = objItr.key().asString(); LOG_DEBUG("Found shader: " << shdName); // find attribute type std::string attributeType = getStringAttr("attributetype", *objItr); if (attributeType == "color"){ Shader<Color> *newShd = getColorShader(shdName, *objItr); renderEnv->shadingEngine->registerShaderColor(shdName, newShd); } else if (attributeType == "float"){ Shader<float> *newShd = getFloatShader(shdName, *objItr); renderEnv->shadingEngine->registerShaderFloat(shdName, newShd); } else{ LOG_ERROR("Unable to parse shader for attribute type: " << attributeType); } } LOG_DEBUG("Done parsing shaders.\n"); break; } } if (!foundShaders) { LOG_WARNING("No shaders found in file " << filename << "."); } }
void Objects::StringDisplay::update() { // Make sure repeated calls to this function don't simply add strings self_displayStrings.clear(); Json::Value strings; strings = self_data["strings"]; if (self_data["external"].isBool()) if (self_data["external"] == true) { string resource = self_data["resource"].asString(); string node = self_data["node"].asString(); strings = Resources::getResourceNode(resource, node); } //Create array of human readable strings. New entry every "self_maxLines" //lines stringstream outputStream; int lineN = 0; for (Json::ValueIterator itr = strings.begin(); itr != strings.end(); itr++) { //Stored as "key" : "value", so extract these string key = itr.key().asString(); Json::Value value = strings[key]; //buffer key and do appropriate thing for value outputStream << key << self_delimiter; if (value.type() == Json::stringValue) outputStream << value.asString(); else if (value.isNumeric()) outputStream << value.asDouble(); outputStream << "\n"; lineN++; if ( lineN == self_maxLines ) { self_displayStrings.push_back(outputStream.str()); lineN = 0; outputStream.str(""); } } //Add remaining string self_displayStrings.push_back( outputStream.str() ); }
void SiteLanguagePackage::decode_from_json_object(const Json::Value &root) { Json::Value tmp; if ( root.isObject() && root.isMember("LanguageMap") ) { const Json::Value map_LanguageMap = root["LanguageMap"]; if ( !map_LanguageMap.isNull() ) { for( Json::ValueIterator it = map_LanguageMap.begin(); it != map_LanguageMap.end(); ++it ) { std::string key = it.key().asString(); LanguageMap[key] = map_LanguageMap[key].asString(); } } } }
bool Level::ReadLevelFile(std::string path) { FileIO fio; if( !fio.LoadFile("Assets/Levels/"+path) || fio.RootKey != "Level" ) return false; Json::Value types = fio.GetChildren(fio.Root); for( Json::ValueIterator i = types.begin(); i != types.end(); ++i ) { std::string type = i.key().asString(); Entity* arch = Factory::BuildArchetype("Assets/Objects/"+type); if( arch == nullptr ) continue; Json::Value objects = (*i)["Entities"]; for( Json::ValueIterator j = objects.begin(); j != objects.end(); ++j ) { Json::Value components = *j; for( Json::ValueIterator k = components.begin(); k != components.end(); ++k ) { std::string key = k.key().asString(); } // Stores Entity name and Json value with components STATIC_LIST.push_back( std::pair<std::string,Json::Value>(type,*j) ); } } return true; }
void JsonParser::parseOptions(Json::Value &root){ LOG_DEBUG("Parsing Options."); bool foundOptions = false; // Options for( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) { std::string key = itr.key().asString(); if (key == "options") { foundOptions = true; // read all standard data int r_pixelSamples = getIntAttr("pixelsamples", *itr); int r_lightSamples = getIntAttr("lightsamples", *itr); int r_mindepth = getIntAttr("mindepth", *itr); int r_maxdepth = getIntAttr("maxdepth", *itr); int r_resolution[2]; getIntArrayAttr("resolution", *itr, 2, r_resolution); std::string r_fileName = getStringAttr("filename", *itr); r_fileName = stringTemplate(r_fileName); // TODO: check for any ones we've skipped and warn the user // TODO: handle errors gracefully // apply to globals LOG_DEBUG("Setting pixel samples to: " << r_pixelSamples); (*renderEnv->globals)[PixelSamples] = (double)r_pixelSamples; LOG_DEBUG("Setting light samples to: " << r_lightSamples); (*renderEnv->globals)[LightSamples] = (double)r_lightSamples; LOG_DEBUG("Setting min trace depth to: " << r_mindepth); (*renderEnv->globals)[MinDepth] = (double)r_mindepth; LOG_DEBUG("Setting max trace depth to: " << r_maxdepth); (*renderEnv->globals)[MaxDepth] = (double)r_maxdepth; LOG_DEBUG("Setting resolution to: " << r_resolution[0] << " * " << r_resolution[1]); (*renderEnv->globals)[ResolutionX] = r_resolution[0]; (*renderEnv->globals)[ResolutionY] = r_resolution[1]; LOG_DEBUG("Setting file output to: " << r_fileName); (*renderEnv->stringGlobals)["fileName"] = r_fileName; // We're done, so we exit out of root iterator loop LOG_DEBUG("Done parsing Options.\n"); break; } } if (!foundOptions) { LOG_WARNING("No options found in file " << filename << "."); } }
void GetBuyedListRequestData::decode_from_json_object(const Json::Value &root) { Json::Value tmp; if ( root.isObject() && root.isMember("contentUuidMap") ) { const Json::Value map_contentUuidMap = root["contentUuidMap"]; if ( !map_contentUuidMap.isNull() ) { for( Json::ValueIterator it = map_contentUuidMap.begin(); it != map_contentUuidMap.end(); ++it ) { std::string key = it.key().asString(); contentUuidMap[key] = map_contentUuidMap[key].asString(); } } } }
void BuyCountData::decode_from_json_object(const Json::Value &root) { Json::Value tmp; if ( root.isObject() && root.isMember("buyCountMap") ) { const Json::Value map_buyCountMap = root["buyCountMap"]; if ( !map_buyCountMap.isNull() ) { for( Json::ValueIterator it = map_buyCountMap.begin(); it != map_buyCountMap.end(); ++it ) { std::string key = it.key().asString(); buyCountMap[key] = map_buyCountMap[key].asString(); } } } }
void CPlayerLevels::AddLevel( const FData& level, const std::string& levelId, std::list<CLevel>& levelList ) { FData value; value = level.get("PlayerId",value); if(!value.isString()) { return; } std::string playerId(value.asString()); value = level.get("PlayerName",value); std::string playerName(value.asString()); value = level.get("PlayerSource",value); std::string playerSource(value.asString()); value = level.get("Name",value); std::string name(value.asString()); value = level.get("Data",value); std::string ldata(value.asString()); value = level.get("thumb",value); std::string lthumb(value.asString()); value = level.get("RDate",value); std::string relativeDate(value.asString()); value = level.get("SDate",value); std::string date(value.asString()); value = level.get("Plays",value); int plays = value.asInt(); value = level.get("Votes",value); int votes = value.asInt(); value = level.get("Score",value); int score = value.asInt(); value = level.get("Rating",value); float rating = value.asFloat(); value = level.get("CustomData",value); CustomData customData; Json::ValueIterator it = value.begin(); for(; it != value.end(); it++) { customData.insert(std::make_pair(it.key().asString(), (*it).asString())); } levelList.push_back( CLevel(name, playerName, playerId, playerSource, ldata, lthumb, votes, plays, rating, score, date, relativeDate, customData, levelId)); }
/* * Parse JSON match data */ void Engine::ParseSnapshotData(const std::vector<uint8_t> &data) { LOGI("Parsing snapshot data"); if (data.size() == 0) { LOGI("Game data not found"); return; } std::string str(data.begin(), data.end()); LOGI("Data: %s", str.c_str()); Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse(str, root); if (!parsingSuccessful) { LOGI("Data parse error"); return; } std::string version = root[JSON_KEY_VERSION].asString(); if (version != JSON_VERSION) { LOGI("Data version mismatch"); return; } //Reset existing data for (int32_t i = 0; i < NUM_GAME_WORLD; ++i) for (int32_t j = 0; j < NUM_GAME_STAGES; ++j) scores_[i][j] = 0; //Level data const Json::Value levels = root[JSON_KEY_LEVELS]; Json::ValueIterator it = levels.begin(); Json::ValueIterator itEnd = levels.end(); while (it != itEnd) { std::string stage = it.key().asString(); int32_t score = (*it).asInt(); LOGI("stage:%s score:%d", stage.c_str(), score); if (map_scores_.find(stage) != map_scores_.end()) *map_scores_[stage] = score; ++it; } }
void BuyRequestData::decode_from_json_object(const Json::Value &root) { Json::Value tmp; if ( root.isObject() && root.isMember("afCoin") ) { tmp = root["afCoin"]; if ( !tmp.isNull() ) { afCoin = tmp.asString(); } } if ( root.isObject() && root.isMember("countAdd") ) { tmp = root["countAdd"]; if ( !tmp.isNull() ) { countAdd = tmp.asString(); } } if ( root.isObject() && root.isMember("contentUuid") ) { const Json::Value map_contentUuid = root["contentUuid"]; if ( !map_contentUuid.isNull() ) { for( Json::ValueIterator it = map_contentUuid.begin(); it != map_contentUuid.end(); ++it ) { std::string key = it.key().asString(); contentUuid[key] = map_contentUuid[key].asString(); } } } }
bool cStatSerializer::LoadStatFromJSON(const Json::Value & a_In) { m_Manager->Reset(); for (Json::ValueIterator it = a_In.begin() ; it != a_In.end() ; ++it) { AString StatName = it.key().asString(); eStatistic StatType = cStatInfo::GetType(StatName); if (StatType == statInvalid) { LOGWARNING("Invalid statistic type \"%s\"", StatName.c_str()); continue; } Json::Value & Node = *it; if (Node.isInt()) { m_Manager->SetValue(StatType, Node.asInt()); } else if (Node.isObject()) { StatValue Value = Node.get("value", 0).asInt(); // TODO 2014-05-11 xdot: Load "progress" m_Manager->SetValue(StatType, Value); } else { LOGWARNING("Invalid statistic value for type \"%s\"", StatName.c_str()); } } return true; }
bool util::PrintJSONTree( Json::Value &root, unsigned short depth /* = 0 */) { depth += 1; printf( " {type=[%d], size=%d}", root.type(), root.size() ); if( root.size() > 0 ) { printf("\n"); for( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) { // Print depth. for( int tab = 0 ; tab < depth; tab++) { printf("-"); } printf(" subvalue("); PrintJSONValue(itr.key()); printf(") -"); PrintJSONTree( *itr, depth); } return true; } else { printf(" "); PrintJSONValue(root); printf( "\n" ); } return true; }
void ApplyOverrides(std::string name, AtNode* node, std::vector<std::string> tags, ProcArgs & args) { bool foundInPath = false; for(std::vector<std::string>::iterator it=args.overrides.begin(); it!=args.overrides.end(); ++it) { Json::Value overrides; if(it->find("/") != std::string::npos) // Based on path { if(name.find(*it) != std::string::npos) { overrides = args.overrideRoot[*it]; foundInPath = true; } } else if(matchPattern(name,*it)) // based on wildcard expression { overrides = args.overrideRoot[*it]; foundInPath = true; } else if(foundInPath == false) { if (std::find(tags.begin(), tags.end(), *it) != tags.end()) { overrides = args.overrideRoot[*it]; } } if(overrides.size() > 0) { for( Json::ValueIterator itr = overrides.begin() ; itr != overrides.end() ; itr++ ) { std::string attribute = itr.key().asString(); const AtNodeEntry* nodeEntry = AiNodeGetNodeEntry(node); const AtParamEntry* paramEntry = AiNodeEntryLookUpParameter(nodeEntry, attribute.c_str()); if ( paramEntry != NULL && attribute!="invert_normals" || attribute == "matte") { Json::Value val = args.overrideRoot[*it][itr.key().asString()]; if( val.isString() ) AiNodeSetStr(node, attribute.c_str(), val.asCString()); else if( val.isBool() ) { if(attribute == "matte") { AiMsgDebug("[ABC] adding enable_matte to %s", AiNodeGetName(node)); AddUserGeomParams(node,"enable_matte",AI_TYPE_BOOLEAN); AiNodeSetBool(node,"enable_matte", val.asBool()); } else { AiNodeSetBool(node, attribute.c_str(), val.asBool()); } } else if( val.isInt() ) { //make the difference between Byte & int! int typeEntry = AiParamGetType(paramEntry); if(typeEntry == AI_TYPE_BYTE) { if(attribute=="visibility") { AtByte attrViz = val.asInt(); // special case, we must determine it against the general viz. AtByte procViz = AiNodeGetByte( args.proceduralNode, "visibility" ); AtByte compViz = AI_RAY_ALL; { compViz &= ~AI_RAY_GLOSSY; if(procViz > compViz) procViz &= ~AI_RAY_GLOSSY; else attrViz &= ~AI_RAY_GLOSSY; compViz &= ~AI_RAY_DIFFUSE; if(procViz > compViz) procViz &= ~AI_RAY_DIFFUSE; else attrViz &= ~AI_RAY_DIFFUSE; compViz &= ~AI_RAY_REFRACTED; if(procViz > compViz) procViz &= ~AI_RAY_REFRACTED; else attrViz &= ~AI_RAY_REFRACTED; compViz &= ~AI_RAY_REFLECTED; if(procViz > compViz) procViz &= ~AI_RAY_REFLECTED; else attrViz &= ~AI_RAY_REFLECTED; compViz &= ~AI_RAY_SHADOW; if(procViz > compViz) procViz &= ~AI_RAY_SHADOW; else attrViz &= ~AI_RAY_SHADOW; compViz &= ~AI_RAY_CAMERA; if(procViz > compViz) procViz &= ~AI_RAY_CAMERA; else attrViz &= ~AI_RAY_CAMERA; } AiNodeSetByte(node, attribute.c_str(), attrViz); } else AiNodeSetByte(node, attribute.c_str(), val.asInt()); } else AiNodeSetInt(node, attribute.c_str(), val.asInt()); } else if( val.isUInt() ) AiNodeSetUInt(node, attribute.c_str(), val.asUInt()); else if( val.isDouble() ) AiNodeSetFlt(node, attribute.c_str(), val.asDouble()); } } } } }