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 << "."); } }
Terr::Terr(const Json::Value& loc, const Json::Value locs, map<string, shared_ptr<Terr>>& terrs) : short_name{get_val("short_name", loc).asString()} , display_name{get_val("display_name", loc).asString()} , has_center{get_val("has_center", loc).asBool()} , adjacent{} , piece{} { terrs[short_name] = shared_ptr<Terr>(this); // sketchy... assert(terrs.find(short_name) != terrs.end()); for(const auto& adj_val : get_val("adjacent", loc)) { string adj_name = adj_val.asString(); if(terrs.find(adj_name) == terrs.end()) { const auto it = find_if(locs.begin(), locs.end(), [&adj_name](const Json::Value& t) { return get_val("short_name", t) == adj_name; }); assert(it != locs.end()); set_terrs(*it, locs, terrs); assert(terrs.find(adj_name) != terrs.end()); // TODO NDEBUG adjacent.push_back(terrs[adj_name]); } } }
// TODO: Clean this one up. inline Transform getTransformAttr(const std::string &name, Json::Value &root){ Json::Value errorVal = Json::Value(-99999); //TODO: Very temp Json::Value value = root.get( name.c_str(), errorVal ); if (value == errorVal) { LOG_ERROR("Can't json attribute: " << name); } Transform trans; if (value.size() > 0) { for( Json::ValueIterator trItr = value.begin() ; trItr != value.end() ; trItr++ ) { Json::Value t = *trItr; if (t.begin().key().asString() == "translate") { double num[3]; int i = 0; Json::Value xyz = *t.begin(); for( Json::ValueIterator xyzItr = xyz.begin() ; xyzItr != xyz.end() ; xyzItr++ ) { Json::Value v = *xyzItr; num[i] = v.asDouble(); i++; } LOG_DEBUG("Translating: " << num[0] << " " << num[1] << " " << num[2]); trans.translate(Vector(num[0], num[1], num[2])); } else if (t.begin().key().asString() == "scale") { double num[3]; int i = 0; Json::Value xyz = *t.begin(); for( Json::ValueIterator xyzItr = xyz.begin() ; xyzItr != xyz.end() ; xyzItr++ ) { Json::Value v = *xyzItr; num[i] = v.asDouble(); i++; } LOG_DEBUG("Scaling: " << num[0] << " " << num[1] << " " << num[2]); trans.scale(num[0], num[1], num[2]); } else if (t.begin().key().asString() == "rotateX") { Json::Value v = *t.begin(); double num = v.asDouble(); LOG_DEBUG("Rotate X: " << num); trans.rotateX(num); } else if (t.begin().key().asString() == "rotateY") { Json::Value v = *t.begin(); double num = v.asDouble(); LOG_DEBUG("Rotate Y: " << num); trans.rotateY(num); } else if (t.begin().key().asString() == "rotateZ") { Json::Value v = *t.begin(); double num = v.asDouble(); LOG_DEBUG("Rotate Z: " << num); trans.rotateZ(num); } } } return trans; }
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; }
// Recursive function to convert JSON --> Lua table static bool push_json_value_helper(lua_State *L, const Json::Value &value, int nullindex) { switch(value.type()) { case Json::nullValue: default: lua_pushvalue(L, nullindex); break; case Json::intValue: lua_pushinteger(L, value.asInt()); break; case Json::uintValue: lua_pushinteger(L, value.asUInt()); break; case Json::realValue: lua_pushnumber(L, value.asDouble()); break; case Json::stringValue: { const char *str = value.asCString(); lua_pushstring(L, str ? str : ""); } break; case Json::booleanValue: lua_pushboolean(L, value.asInt()); break; case Json::arrayValue: lua_newtable(L); for (Json::Value::const_iterator it = value.begin(); it != value.end(); ++it) { push_json_value_helper(L, *it, nullindex); lua_rawseti(L, -2, it.index() + 1); } break; case Json::objectValue: lua_newtable(L); for (Json::Value::const_iterator it = value.begin(); it != value.end(); ++it) { #ifndef JSONCPP_STRING const char *str = it.memberName(); lua_pushstring(L, str ? str : ""); #else std::string str = it.name(); lua_pushstring(L, str.c_str()); #endif push_json_value_helper(L, *it, nullindex); lua_rawset(L, -3); } break; } return true; }
std::list<std::string> CJSONHandler::ParseResources(std::string strJSON) { Json::Value root; // will contains the root value after parsing. Json::Reader reader; std::string resName; std::list<std::string> listResources; bool parsingSuccessful = reader.parse(strJSON, root ); if ( !parsingSuccessful ) { CLog::Log(logERROR, "JSONHandler: Parse resource: no valid JSON data"); return listResources; } for(Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++) { Json::Value valu = *itr; resName = valu.get("slug", "unknown").asString(); if (resName.size() == 0 || resName == "unknown") CLog::Log(logERROR, "JSONHandler: Parse resource: no valid JSON data while iterating"); listResources.push_back(resName); CLog::Log(logINFO, "JSONHandler: found resource on Transifex server: %s", resName.c_str()); }; CLog::Log(logINFO, "JSONHandler: Found %i resources at Transifex server", listResources.size()); return listResources; };
std::map<std::string, CLangcodes> CJSONHandler::ParseTransifexLanguageDatabase(std::string strJSON) { Json::Value root; // will contains the root value after parsing. Json::Reader reader; std::string lang; bool parsingSuccessful = reader.parse(strJSON, root ); if ( !parsingSuccessful ) { CLog::Log(logERROR, "JSONHandler: ParseTXLanguageDB: no valid JSON data"); } std::map<std::string, CLangcodes> mapTXLangs; const Json::Value JLangs = root; for(Json::ValueIterator itr = JLangs.begin() ; itr !=JLangs.end() ; itr++) { Json::Value JValu = *itr; const Json::Value JFields =JValu.get("fields", "unknown"); CLangcodes LangData; LangData.Langcode = JFields.get("code", "unknown").asString(); LangData.Langname = JFields.get("name", "unknown").asString(); LangData.Pluralform = JFields.get("pluralequation", "unknown").asString(); LangData.nplurals = JFields.get("nplurals", 0).asInt(); if (LangData.Langcode != "unknown" && LangData.Langname != "unknown") mapTXLangs[LangData.Langcode] = LangData; else CLog::Log(logWARNING, "JSONHandler: ParseTXLanguageDB: corrupt JSON data found while parsing Language Database from Transifex"); }; return mapTXLangs; };
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 << "."); } }
static void buildWaypointList(WaypointClient* userdata) { WaypointClient* anInstance = (WaypointClient*) userdata; Fl_Input_Choice * fromWPChoice = anInstance->frWps; Fl_Input_Choice * toWPChoice = anInstance->toWps; fromWPChoice->clear(); toWPChoice->clear(); Json::Value waypointsArray = anInstance->getWaypoints().get("waypoints",0); if (waypointsArray.size() == 0) { fromWPChoice->add("EMPTY"); toWPChoice->add("EMPTY"); } else { for (Json::ValueIterator itr = waypointsArray.begin(); itr != waypointsArray.end(); itr++) { Json::Value waypoint = *itr; string name = waypoint["name"].asString(); fromWPChoice->add(name.c_str()); toWPChoice->add(name.c_str()); } } fromWPChoice->value(0); toWPChoice->value(0); SelectedFromWP(NULL, anInstance); }
bool cInventory::LoadFromJson(Json::Value & a_Value) { int SlotIdx = 0; for (Json::Value::iterator itr = a_Value.begin(); itr != a_Value.end(); ++itr, SlotIdx++) { cItem Item; Item.FromJson(*itr); // The JSON originally included the 4 crafting slots and the result slot, so we need to skip the first 5 items: if (SlotIdx < 5) { continue; } // If we loaded all the slots, stop now, even if the JSON has more: if (SlotIdx - 5 >= invNumSlots) { break; } int GridSlotNum = 0; cItemGrid * Grid = GetGridForSlotNum(SlotIdx - 5, GridSlotNum); ASSERT(Grid != nullptr); Grid->SetSlot(GridSlotNum, Item); } // for itr - a_Value[] return true; }
Manifest DappLoader::loadManifest(std::string const& _manifest) { /// https://github.com/ethereum/go-ethereum/wiki/URL-Scheme Manifest manifest; Json::Reader jsonReader; Json::Value root; jsonReader.parse(_manifest, root, false); Json::Value entries = root["entries"]; for (Json::ValueIterator it = entries.begin(); it != entries.end(); ++it) { Json::Value const& entryValue = *it; std::string path = entryValue["path"].asString(); if (path.size() == 0 || path[0] != '/') path = "/" + path; std::string contentType = entryValue["contentType"].asString(); std::string strHash = entryValue["hash"].asString(); if (strHash.length() == 64) strHash = "0x" + strHash; h256 hash = jsToFixed<32>(strHash); unsigned httpStatus = entryValue["status"].asInt(); manifest.entries.push_back(ManifestEntry{ path, hash, contentType, httpStatus }); } return manifest; }
/** * 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; }
qpid::types::Variant::List agocontrol::jsonToVariantList(Json::Value value) { Variant::List list; try { for (Json::ValueIterator it = value.begin(); it != value.end(); it++) { if ((*it).size() > 0) { // cout << "JSON Type: " << (*it).type() << endl; if ((*it).type() == 6) { list.push_back(jsonToVariantList((*it))); } else if ((*it).type() == 7) { list.push_back(jsonToVariantMap((*it))); } } else { if ((*it).isString()) list.push_back( (*it).asString()); if ((*it).isBool()) list.push_back( (*it).asBool()); if ((*it).isInt()) list.push_back( (*it).asInt()); if ((*it).isUInt()) list.push_back( (*it).asUInt()); if ((*it).isDouble()) list.push_back( (*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 list; }
int Response::getMsgList(std::string &s, std:: vector <msgRecord> &vmr) const { Json::Value root; stringToJson(s, root); try { Json::Value json = root["result"][0U]["value"]; for (int i = 0; i != json.size(); i++) { Json::Value temp = json[i]; int srcID, targetID, postTime, msgType; std::string msgText; for (__typeof(temp.begin()) it = temp.begin(); it != temp.end(); it++) { if (it.key().asString() == "srcID") srcID = (*it).asInt(); else if (it.key().asString() == "targetID") targetID = (*it).asInt(); else if (it.key().asString() == "msgText") msgText = (*it).asString(); else if (it.key().asString() == "postTime") postTime = (*it).asInt(); else if (it.key().asString() == "msgType") msgType = (*it).asInt(); } MsgRecord mr(srcID, targetID, msgText, msgType); mr.postTime = postTime; vmr.push_back(mr); } } catch (...) { return ERROR; } return 0; }
int load_config(const char *cfg_root) { Json::Value root; if (this->load_json_cfg(cfg_root, SKILL_CFG_PATH, root) != 0) return -1; for (int i = CAREER_LI_LIANG; i <= CAREER_ZHI_LI; ++i) this->career_skill_map_.insert(i, new ilist<int>()); for(Json::Value::iterator iter = root.begin(); iter != root.end(); ++iter) { int cid = ::atoi(iter.key().asCString()); if (!clsid::is_skill(cid)) { e_log->error("%d is not skill in %s!", cid, SKILL_CFG_PATH); return -1; } skill_cfg_obj *sco = new skill_cfg_obj(); this->skill_cfg_obj_map_.insert(std::make_pair(cid, sco)); if (this->load_json(*iter, sco, cid) != 0) return -1; if (clsid::is_char_skill(cid) && util::is_career_ok(sco->career_)) this->career_skill_map_.find(sco->career_)->push_back(cid); } return 0; }
Model *ResourceManager::loadModel(const Json::Value& value, const std::unordered_map<std::string, ResPtr<Resource> >& externalResources) { Json::Value lods = getMember(value, "lods"); if (not lods.isArray()) { throw std::runtime_error("Unable to get the LODs."); } Model *model = NEW(Model); if (value.isMember("stippledLODs")) { model->mStippledLODs = value["stippledLODs"].asBool(); } for (Json::Value::iterator it = lods.begin(); it != lods.end(); ++it) { Json::Value lod = *it; std::string mesh = getMember(lod, "mesh").asString(); std::string material = getMember(lod, "material").asString(); float distance = getMember(lod, "distance").asFloat(); model->mLODs.push_back(LOD(externalResources.at(mesh).cast<Mesh>(), externalResources.at(material).cast<Material>(), distance)); } model->sortLODs(); return model; }
/** * Deserialize JSON formatted skeleton sequence */ void SkeletonRepresentationSequenceJSON::Deserialize(Json::Value& root) { this->version = root.get("version", 0).asDouble(); size_t frameCount = root.get("frameCount", 0).asUInt(); Json::Value skeletonSequence = root.get("skeletonSequence", Json::nullValue); if (frameCount == 0 || skeletonSequence.isNull()) { root = Json::nullValue; return; } else { size_t index = 0; for (Json::ValueIterator it = skeletonSequence.begin(); it != skeletonSequence.end(); it++) { if ((*it).isNull()) continue; // get pose set for current frame SkeletonRepresentationJSON skeletonFrame; skeletonFrame.Deserialize(*it); push_back(skeletonFrame); index++; } } }
/** * Deserialize set of skeletons */ void SkeletonRepresentationSetJSON::Deserialize(Json::Value& root) { // de-serialize primitives m_version = root.get("version",0).asDouble(); m_frameNumber = root.get("frameNumber",0).asInt(); m_timeStamp = root.get("timeStamp",0).asDouble(); size_t skeletonCount = root.get("skeletonCount",0).asUInt(); // we only use the first skeleton (index = 0) from the data //m_v.assign(skeletonCount, PoseRepresentationPoints()); Json::Value skeletonArray = root.get("skeletons", Json::nullValue); if (!skeletonArray.isNull()) { size_t index = 0; for (Json::ValueIterator it = skeletonArray.begin(); it != skeletonArray.end(); it++) { if (index > 1) break; /// here, we quit after reading the zero index if ((*it).isNull()) continue; index++; } } }
static HMENU menuFromJson(const Json::Value& menuInfo) { if (menuInfo.isArray()) { HMENU menu = ::CreatePopupMenu(); for (auto it = menuInfo.begin(); it != menuInfo.end(); ++it) { const Json::Value& item = *it; UINT id = item.get("id", 0).asUInt(); std::wstring text = utf8ToUtf16(item.get("text", "").asCString()); UINT flags = MF_STRING; if (id == 0 && text.empty()) flags = MF_SEPARATOR; else { if (item.get("checked", false).asBool()) flags |= MF_CHECKED; if (!item.get("enabled", true).asBool()) flags |= MF_GRAYED; const Json::Value& subMenuValue = item.get("submenu", Json::nullValue); if (subMenuValue.isArray()) { HMENU submenu = menuFromJson(subMenuValue); flags |= MF_POPUP; id = UINT_PTR(submenu); } } AppendMenu(menu, flags, id, text.c_str()); } return menu; } return NULL; }
int load_config(const char *cfg_root) { Json::Value root; if (this->load_json_cfg(cfg_root, JING_JI_AWARD_CFG_PATH, root) != 0) return -1; for (Json::Value::iterator iter = root.begin(); iter != root.end(); ++iter) { int id = ::atoi(iter.key().asCString()); if (id >= MAX_AWARD_KIND_COUNT) return -1; jj_award_obj *jao = new jj_award_obj(); this->jj_award_obj_map_.insert(id, jao); jao->rank_min_ = (*iter)["rank_min"].asInt(); jao->rank_max_ = (*iter)["rank_max"].asInt(); jao->bind_diamond_ = (*iter)["bind_zuanshi"].asInt(); jao->coin_ = (*iter)["coin"].asInt(); jao->ji_fen_ = (*iter)["ji_fen"].asInt(); } return 0; }
bool MatchStart::parse(std::string json) { Json::Reader reader; Json::Value root; if (!reader.parse(json, root, false)) { throw std::invalid_argument("Unable to parse json"); } romingSettings.parse(root.get("roamingSettings", Json::nullValue)); clientVersionFromXml = root.get("clientVersionFromXml", Json::nullValue).asString(); clientVersionFromExe = root.get("clientVersionFromExe", Json::nullValue).asString(); mapDisplayName = root.get("mapDisplayName", Json::nullValue).asString(); gameplayID = root.get("gameplayID", Json::nullValue).asString(); regionCode = root.get("regionCode", Json::nullValue).asString(); playerID = root.get("playerID", Json::nullValue).asUInt(); serverName = root.get("serverName", Json::nullValue).asString(); Json::Value vehiclesRoot = root.get("vehicles", Json::nullValue); if (vehiclesRoot.size() > 0) { for (auto it = vehiclesRoot.begin(); it != vehiclesRoot.end(); it++) { std::string key(it.memberName()); Json::Value vehicleRoot = vehiclesRoot.get(key, Json::nullValue); Vehicle value; value.parse(vehicleRoot); vehicles.insert(std::make_pair(key, value)); } } dateTime = root.get("dateTime", Json::nullValue).asString(); mapName = root.get("mapName", Json::nullValue).asString(); playerName = root.get("playerName", Json::nullValue).asString(); battleType = root.get("battleType", Json::nullValue).asUInt(); playerVehicle = root.get("playerVehicle", Json::nullValue).asString(); return true; }
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; }
bool PlayingCards::JsonDeserialization(const std::string &sJsonPlayingCards, std::string &sErrorMessage) { Json::Reader jReader; Json::Value jCards; Json::Value jCard; Card cCard; if (jReader.parse(sJsonPlayingCards, jCards, false)) { m_vCards.clear(); for (Json::ValueIterator it = jCards.begin(); it != jCards.end(); ++it) { jCard = (*it); if (cCard.JsonDeserialization(jCard.toStyledString(), sErrorMessage)) { m_vCards.push_back(cCard); } else { return false; } } return true; } else { sErrorMessage = jReader.getFormattedErrorMessages(); return false; } }
static bool menuFromJson(ITfMenu* pMenu, const Json::Value& menuInfo) { if (pMenu != nullptr && menuInfo.isArray()) { for (Json::Value::const_iterator it = menuInfo.begin(); it != menuInfo.end(); ++it) { const Json::Value& item = *it; UINT id = item.get("id", 0).asUInt(); std::wstring text = utf8ToUtf16(item.get("text", "").asCString()); DWORD flags = 0; Json::Value submenuInfo; ITfMenu* submenu = nullptr; if (id == 0 && text.empty()) flags = TF_LBMENUF_SEPARATOR; else { if (item.get("checked", false).asBool()) flags |= TF_LBMENUF_CHECKED; if (!item.get("enabled", true).asBool()) flags |= TF_LBMENUF_GRAYED; submenuInfo = item["submenu"]; // FIXME: this is a deep copy. too bad! :-( if (submenuInfo.isArray()) { flags |= TF_LBMENUF_SUBMENU; } } pMenu->AddMenuItem(id, flags, NULL, NULL, text.c_str(), text.length(), flags & TF_LBMENUF_SUBMENU ? &submenu : nullptr); if (submenu != nullptr && submenuInfo.isArray()) { menuFromJson(submenu, submenuInfo); } } return true; } return false; }
// Deserialization constructor VertexAttributes::VertexAttributes(const Json::Value& value) : vertexAttributesFrameSize(0) { // We first need to validate that this a Json array if(!value.isArray()) { throw std::runtime_error("VertexAttributes::VertexAttributes(const Json::Value& value) - value must be an array"); } // Iterate through all the Json values for(Json::Value::const_iterator it = value.begin(); it != value.end(); it++) { // The vertex attribute must be a string if(!(*it).isString()) { throw std::runtime_error("VertexAttributes::VertexAttributes(const Json::Value& value) - serialized vertex attributes must be strings"); } // Get the vertex attribute std::string vertexAttribute = (*it).asString(); // Add this attribute by its key addVertexAttributeByStorageKey(vertexAttribute); } }
bool CTestjsoncpp::test_Parse() { std::wstring wstrJson = ReleaseJsonStr(); std::string strJson = wstr2str(wstrJson, CP_UTF8); Json::Reader jsonReader; Json::Value root; jsonReader.parse(strJson, root); std::string strresult = root["result"].asString(); std::cout << "result:" << strresult << std::endl; std::cout << "data:" << std::endl; Json::Value jvData = root["data"]; if(jvData.isArray()) { std::cout << "[" << std::endl; //item for (Json::Value::iterator it = jvData.begin(); it != jvData.end(); ++it) { std::cout << "{" << std::endl; Json::Value item = *it; Json::Value::Members memItem = item.getMemberNames(); //mem in item for (Json::Value::Members::iterator itItem = memItem.begin(); itItem != memItem.end(); ++itItem) { std::string strKey = *itItem; std::string strValue = item[strKey].asString(); std::cout << strKey << ":" << strValue << std::endl; } std::cout << "}" << std::endl; } std::cout << "]" << std::endl; } return false; }
int SData::ParseEPG(Json::Value &parsed, time_t iStart, time_t iEnd, int iChannelNumber, ADDON_HANDLE handle) { XBMC->Log(LOG_DEBUG, "%s", __FUNCTION__); time_t iStartTimestamp; time_t iStopTimestamp; int iEntriesTransfered(0); for (Json::Value::iterator it = parsed.begin(); it != parsed.end(); ++it) { iStartTimestamp = Utils::GetIntFromJsonValue((*it)["start_timestamp"]); iStopTimestamp = Utils::GetIntFromJsonValue((*it)["stop_timestamp"]); if (!(iStartTimestamp > iStart && iStopTimestamp < iEnd)) { continue; } EPG_TAG tag; memset(&tag, 0, sizeof(EPG_TAG)); tag.iUniqueBroadcastId = Utils::GetIntFromJsonValue((*it)["id"]); tag.strTitle = (*it)["name"].asCString(); tag.iChannelNumber = iChannelNumber; tag.startTime = iStartTimestamp; tag.endTime = iStopTimestamp; tag.strPlot = (*it)["descr"].asCString(); PVR->TransferEpgEntry(handle, &tag); iEntriesTransfered++; } return iEntriesTransfered; }
bool cBeaconEntity::LoadFromJson(const Json::Value & a_Value) { m_PosX = a_Value.get("x", 0).asInt(); m_PosY = a_Value.get("y", 0).asInt(); m_PosZ = a_Value.get("z", 0).asInt(); Json::Value AllSlots = a_Value.get("Slots", 0); int SlotIdx = 0; for (Json::Value::iterator itr = AllSlots.begin(); itr != AllSlots.end(); ++itr) { cItem Item; Item.FromJson(*itr); SetSlot(SlotIdx, Item); SlotIdx++; } m_BeaconLevel = (char)a_Value.get("Level", 0).asInt(); int PrimaryEffect = a_Value.get("PrimaryEffect", 0).asInt(); int SecondaryEffect = a_Value.get("SecondaryEffect", 0).asInt(); if ((PrimaryEffect >= 0) && (PrimaryEffect <= (int)cEntityEffect::effSaturation)) { m_PrimaryEffect = (cEntityEffect::eType)PrimaryEffect; } if ((SecondaryEffect >= 0) && (SecondaryEffect <= (int)cEntityEffect::effSaturation)) { m_SecondaryEffect = (cEntityEffect::eType)SecondaryEffect; } return true; }
void CompareJson(json::Value& lhs, json::Value& rhs, json::Value& output) { std::string lstr, rstr; if (rhs.type() != lhs.type()) return; switch (lhs.type()) { case json::Value::tString: lstr = lhs.getString(); rstr = rhs.getString(); if (!lstr.empty() && lstr[0] == '$' && lstr.back() == '$') { size_t slash = lstr.find('/'); std::string cat = lstr.substr(1, slash - 1); std::string name = lstr.substr(slash + 1, lstr.length() - slash - 2); output[cat][name] = rstr; } break; case json::Value::tArray: for (size_t i = 0; i < lhs.length(); ++i) { if (i < rhs.length()) { CompareJson(lhs[i], rhs[i], output); } } break; case json::Value::tObject: for (auto it = lhs.begin(); it != lhs.end(); ++it) { if (rhs.has(it.key())) { CompareJson(*it, rhs[it.key()], output); } } break; } }
void ImportProfileCommand::importKeys(const Json::Value &keys, const Serializer &serializer, KeyStore &store) { for(Json::Value::const_iterator it = keys.begin(), end = keys.end(); it!=end; ++it) { store.insert(serializer.unserialize(*it)); } }