Example #1
0
void Roster::update(const json::Value& data, bool whiny)
{
    if (data.isObject() &&
        data.isMember("id") &&
        data.isMember("user") &&
        data.isMember("name") //&&
        //data.isMember("type")
        ) {
        TraceS(this) << "Updating: " << json::stringify(data, true) << endl;
        std::string id = data["id"].asString();
        Peer* peer = get(id, false);
        if (!peer) {
            peer = new Peer(data);
            add(id, peer);
        } else
            static_cast<json::Value&>(*peer) = data;
    }
    else if (data.isArray()) {
        for (auto it = data.begin(); it != data.end(); it++) {
            update(*it, whiny);
        }
    }
    else {
        std::string error("Bad presence data: " + json::stringify(data));
        ErrorS(this) << error << endl;
        if (whiny)
            throw std::runtime_error(error);
    }
}
Example #2
0
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;
  }
}
Example #3
0
void FileParser::buildSurfaceStruct(const Json::Value& node, const Matrix4& matrix, unordered_map<string, SurfaceStruct>& structMap) const {
  const Json::Value::const_iterator& v = node.begin();
  string name = parseString((*v)["name"], "entity name");
  SurfaceStruct s;
  s.node = node;
  s.obj2world = matrix;
  structMap[name] = s;
}
Example #4
0
void ItemHandler::deserializeItems(Json::Value& root) {
	Item* item;
	
    for (Json::ValueIterator it = root.begin(); it != root.end(); it++) {
		item = new Item();
		item->deserialize(*it);
        this->addItem(item);
    }
}
Example #5
0
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;
    }
}
Example #6
0
vector<Json::Value> ValueToValueVector(const Json::Value& value) {
  vector<Json::Value> result;
  if (value.isNull())
    return result;
  result.reserve(value.size());
  for (auto it = value.begin(); it != value.end(); ++it)
    result.push_back((*it));
  return result;
}
Example #7
0
	Value convert_json_array(const Json::Value &arr)
	{
		std::vector<Value> vals(arr.size());
		std::vector<Value>::iterator oiter = vals.begin();
		Json::Value::const_iterator iiter = arr.begin();
		while (iiter != arr.end())
			*oiter++ = convert_json(*iiter++);
		return value(new_tuple(vals.begin(), vals.end()));
	}
Example #8
0
 bool Model::parseAsDistributions(const Json::Value& root, const std::string& entryName) {
	 Json::Value array;
	 if (!ParserUtils::parseAsArray(root, entryName, &array)) return false;

	 for (Json::Value::iterator iter = array.begin(); iter != array.end(); iter++) {
		 if (!parseAsDistribution(*iter)) return false;
	 }
	 return true;
 }
CWaveContactStatusCollection::CWaveContactStatusCollection(Json::Value & vRoot)
{
	for (Json::Value::iterator iter = vRoot.begin(); iter != vRoot.end(); iter++)
	{
		CWaveContactStatus * lpStatus = new CWaveContactStatus(*iter);

		m_vStatuses[lpStatus->GetEmailAddress()] = lpStatus;
	}
}
Example #10
0
void fromJsonArray(const Json::Value& parent, std::vector<T>& ref) {
  ref.clear();
  ref.reserve(parent.size());
  for (Json::Value::const_iterator it = parent.begin(); it != parent.end(); ++it) {
    T t;
    fromJson(*it, t);
    ref.push_back(t);
  }
}
std::map<std::string, std::string>  CLCodeHandler::GetTranslatorsDatabase(const std::string& strContributorType, const std::string& strProjectName,
                                                                          const CResData& ResData)
{
  std::map<std::string, std::string> mapOfContributors;

  g_HTTPHandler.Cleanup();
  g_HTTPHandler.ReInit(); 

  for (itmapLCodes = m_mapLCodes.begin(); itmapLCodes != m_mapLCodes.end() ; itmapLCodes++)
  {
    std::string strLangCode = itmapLCodes->first;
    std::string strTXLformat = ResData.TRX.LForm;

    g_HTTPHandler.SetLocation("TRX");
    g_HTTPHandler.SetProjectName(ResData.TRX.ProjectName);
    g_HTTPHandler.SetResName("");
    g_HTTPHandler.SetLCode(strLangCode);
    g_HTTPHandler.SetFileName("ContributorList.json");
    g_HTTPHandler.SetDataFile(true);

    std::string strJson = g_HTTPHandler.GetURLToSTR("https://www.transifex.com/api/2/project/"+ strProjectName + "/language/" +
                                                     GetLangFromLCode(strLangCode, strTXLformat) + "/" + strContributorType + "/");
    if (strJson.empty())
      CLog::Log(logERROR, "CLCodeHandler::GetTranslatorsDatabase: error getting translator groups list for project: %s", strProjectName.c_str());

    Json::Value root;   // will contains the root value after parsing.
    Json::Reader reader;

    bool parsingSuccessful = reader.parse(strJson, root );
    if ( !parsingSuccessful )
      CLog::Log(logERROR, "CLCodeHandler::GetTranslatorsDatabase: no valid JSON data downloaded from Transifex");

    const Json::Value JRoot = root;
    const Json::Value JNames = JRoot[strContributorType];

    CLog::Log(logPRINT, "\n%s%s%s ", KMAG, strLangCode.c_str(), RESET);

    std::list<std::string> listNames;

    for(Json::ValueIterator itr = JNames.begin() ; itr !=JNames.end() ; itr++)
    {
      Json::Value JValu = *itr;
      std::string strName =JValu.asString();

      if (strName == "")
        CLog::Log(logERROR, "CJSONHandler::ParseTranslatorsDatabase: no valid JSON data downloaded from Github");

      CLog::Log(logPRINT, "%s%s%s ", KCYN, strName.c_str(), RESET);
      listNames.push_back(strName);
    }

    if (!listNames.empty())
      mapOfContributors[strLangCode] = g_CharsetUtils.CleanTranslatorlist(strJson);
  };
  return mapOfContributors;
}
//Controlla l'esistenza di lfid (uno solo!) nel nodo json "sd" passato e in quelli in esso contenuti. Se non presenti in "rs" li registra usando "device_mac".
//La funzione ritorna:
//- ABORTED se tutti i nuovi sensori erano già registrati,
//- NICE se almeno un nuovo sensore è stato registrato perché non presente,
//- ERROR se almeno un sensore DOVEVA essere registrato ma la registrazione è fallita.
int register_sensor( const string device_mac, const Json::Value& node, const string rs )
{
	int esito=ABORTED, inner_esito=ERROR;
    	string my_sensor_s;
    	string server_response_s;

	//if you find an lfid code in the node..
    	if(node.isMember("lfid"))
    	{
		//check if the sensor already exists:
		my_sensor_s="\"local_feed_id\":"+node.get("lfid",0).asString();
		if (rs.find(my_sensor_s) == std::string::npos)		//NO
    		{
			Json::Value new_sensor;
      			new_sensor["feed_id"]=0;
      			new_sensor["tags"]=node.get("tags",0).asString();
      			new_sensor["local_feed_id"]=node.get("lfid",0).asInt();
			new_sensor["raspb_wifi_mac"]=device_mac;
			esito=http_post_auth( params["report"].get("API_URL","").asString() + "devices/" +device_mac+"/feeds", new_sensor.toStyledString(), server_response_s);
    			//cerr<<"\nRISPOSTA SERVER SU REGISTER SENSOR "<<node.get("lfid",0).asString()<<":\n"<<server_response_s<<endl;
		}
		else							//YES
		{
			cerr<<"This sensor was already registered... ";
			esito=ABORTED;
		}
    	}
    	//otherwise maybe the attributes may contain lfids..
    	else
    	{
	    	for(Json::Value::iterator i = node.begin(); i !=node.end(); ++i)
		{
			Json::Value element = (*i);
			//END CONDITION: if the attribute contains other attributes, recursively call myself
			if(element.size()!=0)
			{
				inner_esito=register_sensor(device_mac, element, rs);
				//PROPAGAZIONE STATO DI ERRORE
				//esito deve riportare l'errore più grave avvenuto in una delle sottochiamate (inner_esito)
				if(inner_esito!=esito && esito!=ERROR)			//Verifica solo se ci sono stati cambiamenti (se esito era ERROR non ci importa più)
				{
					if(inner_esito != ABORTED) esito = inner_esito;		//se esito era ABORTED, inner_esito avrà riportato un cambiamento: reg. effettuata (NICE) o fallita (ERROR)
												//se esito era NICE, l'algoritmo va comunque bene.
				}
			}
		
		}
	}
	
	//Esito riporterà:
	//- ABORTED se i sensori erano già tutti registrati,
	//- NICE se almeno una registrazione è avvenuta (TUTTE con successo),
	//- ERROR se almeno una registrazione era necessaria MA è fallita.
	return esito;	
	
}
Example #13
0
int main(int argc, char** argv) {

  std::string script = "/xchip/gistic/Jeremiah/GIT/SeqLib/test.json";
  const string document = GetScriptContents(script);

  // set up JsonCPP reader and attempt to parse script
  Json::Value root;
  Json::Reader reader;
  if ( !reader.parse(document, root) ) {
    // use built-in error reporting mechanism to alert user what was wrong with the script
    cerr  << "bamtools filter ERROR: failed to parse script - see error message(s) below" << endl;
    return false;     
  }

  // see if root object contains multiple filters
  const Json::Value filters = root["filters"];

  cerr << " root size " << root.size() << std::endl;
  cerr << " filters size " << filters.size() << std::endl;

  // iterate over any filters found
  int filterIndex = 0;
  Json::Value::const_iterator filtersIter = filters.begin();
  Json::Value::const_iterator filtersEnd  = filters.end();
  for ( ; filtersIter != filtersEnd; ++filtersIter, ++filterIndex ) {
    Json::Value filter = (*filtersIter);
            
    // convert filter index to string
    string filterName;
      
    // if id tag supplied
    const Json::Value id = filter["id"];
    if ( !id.isNull() ) 
      filterName = id.asString();


    // use array index 
    else {
      stringstream convert;
      convert << filterIndex;
      filterName = convert.str();
    }

    cerr << "filter " << filterName << std::endl;            
    // create & parse filter 
    bool success = true;
    success &= ParseFilterObject(filterName, filter);
  }

  /// make mini rules
  cerr << " ... maing mini rules " << endl;
  
  SeqLib::MiniRulesCollection mrc(script);


}
Example #14
0
channel_config::channel_config(const Json::Value& value)
    : config(value),
    zero_delay(value["zero_delay"].asInt()),
    one_delay(value["one_delay"].asInt()),
    warm(value["warm"].asInt())
{
    Json::Value msg = value["msg"];
    bits.resize(msg.size());
    std::transform(msg.begin(), msg.end(), bits.begin(), [](const Json::Value& v){return v.asBool();});
}
Example #15
0
void ActorCreator::AddComponent( int32_t componentId, Json::Value& setters )
{
    std::auto_ptr<PropertyLoaderBase<Component> > compLoader = mComponentLoaderFactory( componentId );
    if( setters.isArray() && !setters.empty() )
    {
        compLoader->Load( *setters.begin() );
    }

    mComponentLoaders.insert( componentId, static_cast<ComponentLoader_t*>( compLoader.release() ) );
}
Example #16
0
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 << ".");
    }

}
Example #17
0
static void streamMetaInformationCb(hbm::streaming::StreamClient& stream, const std::string& method, const Json::Value& params)
{
	if (method == hbm::streaming::META_METHOD_AVAILABLE) {
		// simply subscibe all signals that become available.
		hbm::streaming::signalReferences_t signalReferences;
		for (Json::ValueConstIterator iter = params.begin(); iter!= params.end(); ++iter) {
			const Json::Value& element = *iter;
			signalReferences.push_back(element.asString());
		}

		try {
			stream.subscribe(signalReferences);
			std::cout << __FUNCTION__ << "the following " << signalReferences.size() << " signal(s) were subscribed: ";
		} catch(const std::runtime_error& e) {
			std::cerr << __FUNCTION__ << "error '" << e.what() << "' subscribing the following signal(s): ";
		}

		for(hbm::streaming::signalReferences_t::const_iterator iter=signalReferences.begin(); iter!=signalReferences.end(); ++iter) {
			std::cout << "'" << *iter << "' ";
		}
		std::cout << std::endl;
	} else if(method==hbm::streaming::META_METHOD_UNAVAILABLE) {

		std::cout << __FUNCTION__ << "the following signal(s) are not available anyore: ";

		for (Json::ValueConstIterator iter = params.begin(); iter!= params.end(); ++iter) {
			const Json::Value& element = *iter;
			std::cout << element.asString() << ", ";
		}
		std::cout << std::endl;
	} else if(method==hbm::streaming::META_METHOD_ALIVE) {
		// We do ignore this. We are using TCP keep alive in order to detect communication problems.
	} else if(method==hbm::streaming::META_METHOD_FILL) {
		if(params.empty()==false) {
			unsigned int fill = params[0u].asUInt();
			if(fill>25) {
				std::cout << stream.address() << ": ring buffer fill level is " << params[0u].asUInt() << "%" << std::endl;
			}
		}
	} else {
		std::cout << __FUNCTION__ << " " << method << " " << Json::FastWriter().write(params) << std::endl;
	}
}
Example #18
0
CRpcHelper::full_booklist CRpcHelper::GetFullBookList()
{
    full_booklist result;
    Json::Value ret = json_from_string( m_rpc->Send( "listaddressgroupings" ) );

    std::stack<Json::Value> stk;
    stk.push( ret );
    while( stk.size() )
    {
        const Json::Value rv = stk.top();
        stk.pop();
        if( rv.isArray() || rv.isObject() )
        {
            if( rv.size() > 0 )
            {
                if( rv[UINT( 0 )].isString() && rv.size() >= 2 )
                {
                    assert( rv[1].isDouble() );
                    addr_ext_info nv;
                    address_str addr = address_str( rv[UINT( 0 )].asString() );
                    nv.balance = rv[1].asDouble();
                    if( rv.size() >= 3 )
                    {
                        nv.label = label_str( rv[2].asString() );
                    }
                    bool ok = result.insert( std::make_pair( addr, nv ) ).second;
                    assert( ok );
                }
                else
                {
                    for( Json::Value::const_iterator it = rv.begin(); it != rv.end(); ++it )
                    {
                        stk.push( *it );
                    }
                }
            }
        }
        else
        {
            assert( 0 );
        }
    }

    mini_booklist minis = GetMiniBookList();
    for( mini_booklist::const_iterator it = minis.begin(); it != minis.end(); ++it )
    {
        addr_ext_info ar;
        ar.label = it->second;
        ar.balance = 0;
        result.insert( std::make_pair( it->first, ar ) ).second;

    }

    return result;
}
bool updateRegistry(Json::Value &jsonRoot, Json::Value &outputRoot)
{
	bool success = true;
	for (Json::ValueIterator iter = jsonRoot.begin(); iter != jsonRoot.end(); iter++) {
		Json::Value solutionsRoot = jsonRoot.get(iter.memberName(), Json::Value());
		Json::Value solutionsOutput;
		for(Json::ValueIterator itr = solutionsRoot["settings"].begin() ; itr != solutionsRoot["settings"].end() ; itr++ )
		{
			bool missingValue = false;
			Json::Value currentOption;
			const char * path = solutionsRoot["options"]["path"].asCString();
			const char * valueName = itr.memberName();
			long valueToSet = solutionsRoot["settings"][valueName].asUInt();
			
		    wstring updatedPath = toWideChar(path);
			wstring updatedValueName = toWideChar(valueName);
			long value = -1;
			try
			{
				value = getDwordValue(hKeyFromString(solutionsRoot["options"]["hKey"].asCString()), updatedPath.c_str(), updatedValueName.c_str());
			} catch (int exCode)
			{
				currentOption["statusCode"] = exCode;
				currentOption["oldValue"] = Json::Value();
				currentOption["newValue"] = Json::Value();
				success = false;
				missingValue = true;
			}

			bool valueSet = setDwordValue(hKeyFromString(solutionsRoot["options"]["hKey"].asCString()), updatedPath.c_str(), updatedValueName.c_str(), valueToSet);
			if (missingValue)
			{
				currentOption["oldValue"] = Json::Value();
			} else {
				currentOption["oldValue"] = value;
			}
			try
			{
				currentOption["newValue"] = getDwordValue(hKeyFromString(solutionsRoot["options"]["hKey"].asCString()), updatedPath.c_str(), updatedValueName.c_str());
			} catch (int exceptionCode) {
				// TODO Handle gracefully.
			}
			if (!valueSet)
			{
				success = false;
				currentOption["newValue"] = value;
			}
		
			solutionsOutput[valueName] = currentOption;
		}
		outputRoot[iter.memberName()]["results"] = solutionsOutput;
	}
	return success;
}
Example #20
0
void
ValueTest::checkConstMemberCount( const Json::Value &value, unsigned int expectedCount )
{
   unsigned int count = 0;
   Json::Value::const_iterator itEnd = value.end();
   for ( Json::Value::const_iterator it = value.begin(); it != itEnd; ++it )
   {
      ++count;
   }
   JSONTEST_ASSERT_EQUAL( expectedCount, count ) << "Json::Value::const_iterator";
}
Example #21
0
void LsExecutor::execute(Json::Value &fa,int &dep){
    try{
        for(Json::Value::iterator it=fa.begin();it!=fa.end();it++){
            Json::Value key=it.key();
            Json::FastWriter writer;
            cout<<writer.write(key);
        }
    }
    catch(int){
    }
}
Example #22
0
bool CRazberry::GetUpdates()
{
	std::string sResult;
#ifndef	DEBUG_ZWAVE_INT
	std::string szURL=GetControllerURL();
	bool bret;
	bret=HTTPClient::GET(szURL,sResult);
	if (!bret)
	{
		_log.Log(LOG_ERROR,"Razberry: Error getting update data!");
		return 0;
	}
#else
	sResult=readInputTestFile("update.json");
#endif
	Json::Value root;

	Json::Reader jReader;
	bool ret=jReader.parse(sResult,root);
	if (!ret)
	{
		_log.Log(LOG_ERROR,"Razberry: Invalid data received!");
		return 0;
	}

	for (Json::Value::iterator itt=root.begin(); itt!=root.end(); ++itt)
	{
		std::string kName=itt.key().asString();
		const Json::Value obj=(*itt);

		if (kName=="updateTime")
		{
			std::string supdateTime=obj.asString();
			m_updateTime=(time_t)atol(supdateTime.c_str());
		}
		else if (kName=="devices")
		{
			parseDevices(obj);
		}
		else
		{
			std::vector<std::string> results;
			StringSplit(kName,".",results);

			if (results.size()>1)
			{
				if (kName.find("lastReceived")==std::string::npos)
					UpdateDevice(kName,obj);
			}
		}
	}

	return true;
}
Example #23
0
void cEnderChestEntity::LoadFromJson(const Json::Value & a_Value, cItemGrid & a_Grid)
{
	int SlotIdx = 0;
	for (Json::Value::iterator itr = a_Value.begin(); itr != a_Value.end(); ++itr)
	{
		cItem Item;
		Item.FromJson(*itr);
		a_Grid.SetSlot(SlotIdx, Item);
		SlotIdx++;
	}
}
Example #24
0
Json::Value createJSON(PSLIBSZHASH pHashSynoInfoCurrent, PSLIBSZHASH pHashSynoInfoDefault)
{
	Json::Value root;

	Json::Value jsonHashAll;

	PSLIBSZLIST pListSynoInfoKey = SLIBCSzListAlloc(0);
	SLIBCSzHashEnumKey(pHashSynoInfoCurrent, &pListSynoInfoKey);

	int count = SLIBCSzHashPairNum(pHashSynoInfoCurrent);
	for(int i = 0; i < count; i++) {
		const char* szKey = SLIBCSzListGet(pListSynoInfoKey, i);
		const char* szValue = SLIBCSzHashGetValue(pHashSynoInfoCurrent, szKey);
		Json::Value item=jsonHashAll.get(szKey, Json::Value());

		item[KEY_KEY] = szKey;
		item[KEY_USER_SETTING] = szValue;
		jsonHashAll[szKey]=item;
	}
	SLIBCSzListFree(pListSynoInfoKey);


	pListSynoInfoKey = SLIBCSzListAlloc(0);
	SLIBCSzHashEnumKey(pHashSynoInfoDefault, &pListSynoInfoKey);

	count = SLIBCSzHashPairNum(pHashSynoInfoDefault);
	for(int i = 0; i < count; i++) {
		const char* szKey = SLIBCSzListGet(pListSynoInfoKey, i);
		const char* szValue = SLIBCSzHashGetValue(pHashSynoInfoDefault, szKey);
		Json::Value item=jsonHashAll.get(szKey, Json::Value());

		item[KEY_KEY] = szKey;
		item[KEY_DEFAULT_SETTING] = szValue;
		jsonHashAll[szKey]=item;
	}
	SLIBCSzListFree(pListSynoInfoKey);


	Json::Value items(Json::arrayValue);
	for(Json::Value::iterator iter = jsonHashAll.begin(); iter != jsonHashAll.end(); iter++) {
		std::string sKey = (*iter)[KEY_KEY].asString();
		std::string sDefaultSetting = (*iter)[KEY_DEFAULT_SETTING].asString();
		std::string sUserSetting  = (*iter)[KEY_USER_SETTING].asString();

		Json::Value item;
		item[KEY_KEY] = sKey;
		item[KEY_DEFAULT_SETTING] = sDefaultSetting;
		item[KEY_USER_SETTING] = sUserSetting;
		items.append(item);
	}

	root[KEY_ITEMS] = items;
	return root;
}
Example #25
0
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;
};
int list_object (const Json::Value& list, const bool withNumbers, const bool listKeys, vector<string> keys, const bool displayObjectKeysInsideArray) {
    
    // NOTE: listing the keys of an array of objects makes no sense.
    
    Value::iterator listIterator;
    vector <string> keyList;
    int counter = 0;
    
    if (list.isObject())
        keyList = list.getMemberNames();
    
    // Iterate through the contents of a JSON Value
    for (listIterator = list.begin(), counter = 0; listIterator != list.end(); counter++, listIterator++) {
        string extraText;
        
        //Add numbers, and pad with spaces as necessary
        if (withNumbers) {
            extraText = to_string(counter + 1) + ":";
            
            //Space out output
            while (extraText.length() < 7)
                extraText += " ";
        }
        
        if (listKeys == true && list.isObject()) //it's an object and listKeys is listed, iterator lists the keys
            cout << extraText << keyList[counter] << endl;
        else if (!keys.empty() && list.isObject()) { //its an object/map, the keys aren't to be listed, and there are specific key(s) that want to be listed, iterator lists key(s) contents on a single line
            bool found = false; //Indicates if a key was found
            
            //Search the key pointed to in the current loop for matches with the keys desired, indicate if search is successful
            for (auto i = keys.begin(); i != keys.end() && !found; i++) {
                if (keyList[counter] == *i)
                    found = true;
            }
            
            // if a match was found, write the key's contents to extra and send extra to output, else decrement counter so that the next object is logically numbered on the output
            if (found) {
                extraText += list.get(keys.back(), Json::Value()).asString() + " ";
                cout << extraText << endl;
            }
            else
                --counter;
        }
        else if (!keys.empty() && list.isArray() && list.size() > 0 && list[0].isObject() && displayObjectKeysInsideArray) { //lists keys in object inside array, iterator goes through objects - not keys
            for (auto key = keys.begin(); key != keys.end(); key++)
                extraText += list[counter].get(*key, Json::Value()).asString() + " ";
            cout << extraText << endl;
        }
        else //If all else fails, just spit the raw contents of the json value out to screen
            cout << extraText << *listIterator << endl;
    }
    
    return counter;
}
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();
            }
        }
    }   
}
Example #28
0
void Inventory::load(const Json::Value& inventoryJson)
{
   m_items.clear();

   for(Json::Value::iterator iter = inventoryJson.begin(); iter != inventoryJson.end(); ++iter)
   {
      int itemNum, itemQuantity;
      itemNum = (*iter)[Inventory::ITEM_NUM_ATTRIBUTE].asInt();
      itemQuantity = (*iter)[Inventory::ITEM_QUANTITY_ATTRIBUTE].asInt();
      m_items.emplace_back(itemNum, itemQuantity);
   }
}
Example #29
0
    std::list<Ogre::String> JsonUtils::asStringsList(Json::Value const &value, std::list<Ogre::String> defaultValue, Ogre::String defaultItemValue)
    {
        if(value.isNull() || !value.isArray())
            return defaultValue;

        std::list<Ogre::String> output;

        for(Json::ValueIterator it = value.begin(); it != value.end(); ++it)
            output.push_back(asString(*it, defaultItemValue));

        return output;
    }
Example #30
0
    std::list<unsigned long> JsonUtils::asUnsignedLongList(const Json::Value &value, const std::list<unsigned long> defaultValue, unsigned long defaultItemValue)
    {
        if(value.isNull() || !value.isArray())
            return defaultValue;

        std::list<unsigned long> output;

        for(Json::ValueIterator it = value.begin(); it != value.end(); ++it)
            output.push_back(asUnsignedLong(*it, defaultItemValue));

        return output;
    }