Example #1
0
//-----------------------------------------------------------------------------------
void EngineConfig::LoadSceneSettings(Json::Value root, Json::Reader reader)
{
	Json::Value settings = root["scenes"];
	int componentCount = settings.size();

	for( int i=0; i< componentCount; ++i )
	{
		Json::Value componentVal = settings[i];
		Json::Value::Members members = componentVal.getMemberNames();

		map<std::string, std::string> mapValues;
		for( Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it)
		{
			std::string memberName = *it;
			std::string value = componentVal[memberName].asString();
			
			mapValues[memberName] = value;

		}

		std::string sceneName = mapValues["name"];
		std::string fileName = mapValues["file"];

		SceneData *sceneData = new SceneData( sceneName, fileName );

		scenes[sceneName] = sceneData;
	}

	settings = root["startscene"];
	startScene = scenes[settings.asCString()];
}
FB::variant jsonValueToVariant( Json::Value root )
{
    Json::Value def;
    if (root.isString())
        return root.asString();
    else if (root.isBool())
        return root.asBool();
    else if (root.isDouble())
        return root.asDouble();
    else if (root.isInt())
        return root.asInt();
    else if (root.isUInt())
        return root.asUInt();
    else if (root.isNull())
        return FB::FBNull();
    else if (root.isArray()) {
        FB::VariantList outList;
        for (size_t i = 0; i < root.size(); ++i) {
            outList.push_back(jsonValueToVariant(root.get(i, def)));
        }
        return outList;
    } else if (root.isObject()) {
        Json::Value::Members members = root.getMemberNames();
        FB::VariantMap outMap;
        for (Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it)
        {
            outMap[*it] = jsonValueToVariant(root.get(*it, def));
        }
        return outMap;
    } else {
        return FB::FBVoid();
    }
}
Example #3
0
int Database::load()
{
    if (open() != 0)
        return -1;
    Json::Reader reader;
    if (!reader.parse(file_in, root, false)){
        ERR("Json reader parse error, maybe empty file\n");
        root.clear();
        return -1;
    }
    try {
        Json::Value::Members member = root.getMemberNames();
        Json::Value::Members::iterator it = member.begin();
        for (; it != member.end(); it++){
            if (load_obj(string_to_wstring(*it)) == NULL)
                ERR("Load object error\n");
        }
    }
    catch (Json::LogicError & e) {
    	cout << e.what() << endl;
        ERR("Json file data not correct\n");
        close_json();
        return -1;
    }
    
    return 0;
}
/**
 * Updates a configuration map with the given json node.
 *
 * @param configurationMap The configuration map to be updated.
 * @param currentNode The node to be used to update the configuration map.
 */
void JsonConfigurationParser::updateConfigurationMap(ConfigurationMap *configurationMap, const Json::Value &currentNode) {
    // retrieves the menber names
    Json::Value::Members currentNodeMembers = currentNode.getMemberNames();

    // retrieves the current node members iterator
    Json::Value::Members::iterator currentNodeMembersIterator = currentNodeMembers.begin();

    // itearates over all the current node members
    while(currentNodeMembersIterator != currentNodeMembers.end()) {
        // retrieves the property name
        std::string &propertyName = *currentNodeMembersIterator;

        // retrieves the property value
        Json::Value propertyValue = currentNode[propertyName];

        // creates the configuration value
        ConfigurationValue *configurationValue = this->createConfigurationValue(propertyValue);

        // sets the propery in the configuration map
        configurationMap->setProperty(propertyName, configurationValue);

        // increments the current node members iterator
        currentNodeMembersIterator++;
    }
}
Example #5
0
configGoodsItem*  CData::getConfigOfGoods(int tempid)
{
    
    if(m_config_goods_dic->count() < 1)
    {
//        const char * path=FileUtils::getInstance()->fullPathForFilename("itemconfig.json").c_str();
//        ifstream ifs;
//        ifs.open(path);
//        assert(ifs.is_open());
        Json::Reader reader;
        Json::Value root;
        Json::Value items;
        
        Json::Value::Members members;
        
//        Json::Value::iterator it;
        Json::Value::Members::iterator it;
        
        string path = FileUtils::getInstance()->fullPathForFilename("item.json");
        __String* str = __String::createWithContentsOfFile(path.c_str());
            
        if(reader.parse(str->getCString(), root)){
            
            members = root.getMemberNames();
            it = members.begin();
            while (it != members.end()) {
                
                items = root[std::string(*it)];
                
                configGoodsItem * item= new configGoodsItem();
                char inttostr[20]="";
                sprintf(inttostr, "%d",tempid);
                
                item->bodytype=items["bodyType"].asInt();
                item->name=items["name"].asString();
                item->pinzhi=items["baseQuality"].asInt();
                item->des=items["description"].asString();
                item->tempid = items["id"].asInt();
                item->icon = items["icon"].asInt();
                item->maxexp = items["maxexp"].asInt();
                item->growTemp = items["growTemp"].asInt();
                item->comprice = items["comprice"].asInt();
                item->compound = items["compound"].asInt();
                
                
                m_config_goods_dic->setObject(item, item->tempid);
                
                it++;
            }
        
         //   ifs.close();
    
        }

    }
    
    
    return (configGoodsItem*)m_config_goods_dic->objectForKey(tempid);
    
}
Example #6
0
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;
}
Example #7
0
void QueryParser::buildTasks(
    const Json::Value &query,
    std::vector<std::shared_ptr<Task> > &tasks,
    task_map_t &task_map) const {
    Json::Value::Members members = query["operators"].getMemberNames();
    std::string papiEventName = getPapiEventName(query);
    for (unsigned i = 0; i < members.size(); ++i) {
        Json::Value planOperationSpec = query["operators"][members[i]];
        std::string typeName = planOperationSpec["type"].asString();
        std::shared_ptr<PlanOperation> planOperation = QueryParser::instance().parse(
                    typeName, planOperationSpec);
        planOperation->setEvent(papiEventName);
        setInputs(planOperation, planOperationSpec);
        if (auto para = std::dynamic_pointer_cast<ParallelizablePlanOperation>(planOperation)) {
            para->setPart(planOperationSpec["part"].asUInt());
            para->setCount(planOperationSpec["count"].asUInt());
        } else {
            if (planOperationSpec.isMember("part") || planOperationSpec.isMember("count")) {
                throw std::runtime_error("Trying to parallelize " + typeName + ", which is not a subclass of Parallelizable");
            }
        }

        planOperation->setOperatorId(members[i]);
        if (planOperationSpec.isMember("core"))
            planOperation->setPreferredCore(planOperationSpec["core"].asInt());
        // check for materialization strategy
        if (planOperationSpec.isMember("positions"))
            planOperation->setProducesPositions(!planOperationSpec["positions"].asBool());
        tasks.push_back(planOperation);
        task_map[members[i]] = planOperation;
    }
}
Example #8
0
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;
}
Example #9
0
void JsonParameters::importParameters(Json::Value parametersImport)
{
    if (parametersImport.isObject()) {
        Json::Value::Members members = parametersImport.getMemberNames();
        Json::Value::Members::iterator it;

        for (it=members.begin(); it!=members.end(); it++) {
            string name = *it;
            JsonParameter *parameter = getParameter(name);
            if (parameter != NULL) {
                if (parameter->canDeserialize(parametersImport[name])) {
                    parameter->deserialize(parametersImport[name]);
                } else {
                    std::cerr << "Can't load parameter " << name << std::endl;
                }
            } else {
                std::cerr << "Non-existent parameter: " << name << std::endl;
            }
        }
    } else {
        if (!parametersImport.isNull()) {
            std::cerr << "Parameters values should be an object" << std::endl;
        }
    }
}
Example #10
0
void SceneLoader::Load(const char* strFileName, GameObject *rootGameObject)
{
	GameObject *pGo = 0;
	Json::Value root;
	Json::Reader reader;

	const char* jsonText = ReadFileIntoString( strFileName );

	if( !reader.parse( jsonText, root ) )
	{
		return;
	}


	Json::Value componentsVal = root["objects"];
	int componentCount = componentsVal.size();

	for( int i=0; i< componentCount; ++i )
	{
		Json::Value componentVal = componentsVal[i];
		Json::Value::Members members = componentVal.getMemberNames();
		
		std::map<std::string, std::string> mapParams;
		for( Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it)
		{
			std::string memberName = *it;
			std::string value = componentVal[memberName].asString();

			mapParams[memberName] = value;
		}

		CreateSceneObject( rootGameObject, mapParams );
	}
}
Example #11
0
//virtual 
bool AnimationLogic::init(  const JsonValueRef json )
{
	m_states.clear();

	if( !json.isMember("states") || !json.isMember("events") ) return false;

	for( int i=0; i< json["events"].size(); i++)
	{
		m_events.push_back( json["events"][i].asString() );
	}

	m_defaultState = json.get("default", "idle").asString();

	Json::Value::Members states = json["states"].getMemberNames();
	for(int i=0; i< states.size(); i++)
	{
		JsonValueRef stateObj = json["states"][states[i]];
		Json::Value::Members events = stateObj.getMemberNames();

		AnimState animState;
		animState.name = states[i];
		CCLOG(" animState: %s", animState.name.c_str() );
		for( int j=0; j< events.size(); j++)
		{
			std::string newState = stateObj[ events[j] ].asString();
			animState.transitionTable[ events[j] ] = newState;

			CCLOG("  %s => %s", events[j].c_str(), newState.c_str() );
		}

		m_states[ states[i] ] = animState;
	}

	return true;
}
Example #12
0
bool KsCardMsg::parseJsonData(const std::string& rootname,Json::Value &root)
{
	size_t i;
	Json::Value::Members mbs = root.getMemberNames();
	++parseLevel_;
	if(parseLevel_>2)
		return false;
	for(i = 0;i < mbs.size(); ++i)
	{
		Json::Value& clt = root[mbs[i]];
		std::string fullname = rootname;
		if(rootname.length() > 0)
			 fullname += ".";
		fullname += mbs[i];
		if(clt.isArray() || clt.isObject())
		{
			if(!parseJsonData(fullname,clt))
				return false;
		}
		else
		{
			msg_field_.insert(PARA_MAP_TYPE::value_type(fullname,root.get(mbs[i],"").asString()));
		}
	}
	return true;
}
Example #13
0
void Registry::Interface::_parseWidgets(Json::Value& value,
                                        const Engine::Object& loader) {
  unsigned int index = _spans.size() - 1;
  for (Json::Value::iterator it = value["widgets"].begin();
        it != value["widgets"].end();
        ++it) {
    if ((*it).isObject()) {
      if ((*it).isMember("widget")) {
        _spans[index]++;
        const char* widget_name = (*it)["widget"].asCString();

        const Registry::Widget& widget = loader.loadWidget(widget_name);
        Apsis::World::Object& object = *(new Apsis::World::Object);

        if ((*it).isMember("properties")) {
          Json::Value::Members members = (*it)["properties"].getMemberNames();
          for (Json::Value::Members::iterator property_it = members.begin();
                property_it != members.end();
                ++property_it) {
            const char* name = (*property_it).c_str();
            unsigned int property_id = Apsis::Registry::Property::id(name);

            if ((*it)["properties"][name].isDouble()) {
              object.set(property_id, (*it)["properties"][name].asDouble());
            }
            else if ((*it)["properties"][name].isString()) {
              object.set(property_id, (*it)["properties"][name].asCString());
            }
            else if ((*it)["properties"][name].isIntegral()) {
              object.set(property_id, (long)(*it)["properties"][name].asInt());
            }
          }
        }

        // Defaults
        for (unsigned int i = 0; i < widget.propertyCount(); i++) {
          const char* name = widget.propertyName(i);
          const char* def  = widget.propertyDefault(i);

          if (!object.has(name)) {
            object.set(name, def);
          }
        }

        // Push to tree
        _widgets.push_back(&widget);
        _objects.push_back(&object);

        // Child windows
        _spans.push_back(0);
        if ((*it).isMember("widgets")) {
          _parseWidgets(*it, loader);
        }
      }
    }
    else {
      throw "Interface file's 'widgets' section is malformed.";
    }
  }
}
  void Configuration::SetupRegisteredUsers(MongooseServer& httpServer)
  {
    boost::mutex::scoped_lock lock(globalMutex_);

    httpServer.ClearUsers();

    if (!configuration_.isMember("RegisteredUsers"))
    {
      return;
    }

    const Json::Value& users = configuration_["RegisteredUsers"];
    if (users.type() != Json::objectValue)
    {
      LOG(ERROR) << "Badly formatted list of users";
      throw OrthancException(ErrorCode_BadFileFormat);
    }

    Json::Value::Members usernames = users.getMemberNames();
    for (size_t i = 0; i < usernames.size(); i++)
    {
      const std::string& username = usernames[i];
      std::string password = users[username].asString();
      httpServer.RegisterUser(username.c_str(), password.c_str());
    }
  }
  static void RegisterUserContentType()
  {
    if (configuration_.isMember("UserContentType"))
    {
      const Json::Value& parameter = configuration_["UserContentType"];

      Json::Value::Members members = parameter.getMemberNames();
      for (size_t i = 0; i < members.size(); i++)
      {
        std::string info = "\"" + members[i] + "\" = " + parameter[members[i]].toStyledString();
        LOG(INFO) << "Registering user-defined attachment type: " << info;

        if (!parameter[members[i]].asBool())
        {
          LOG(ERROR) << "Not a number in this user-defined attachment type: " << info;
          throw OrthancException(ErrorCode_BadParameterType);
        }

        int contentType = parameter[members[i]].asInt();

        try
        {
          RegisterUserContentType(contentType, members[i]);
        }
        catch (OrthancException&)
        {
          LOG(ERROR) << "Cannot register this user-defined attachment type: " << info;
          throw;
        }
      }
    }
  }
Example #16
0
void readJson() {
    using namespace std;
    std::string strValue = "{\"name\":\"json\",\"array\":[{\"cpp\":\"jsoncpp\",\"cpp1\":\"jxx\"},{\"java\":\"jsoninjava\"},{\"php\":\"support\"}]}";

    Json::Reader reader;
    Json::Value value;

    if (reader.parse(strValue, value))
    {
        std::string out = value["name"].asString();
        //std::cout << out << std::endl;
        const Json::Value arrayObj = value["array"];

        for (int i=0; i<arrayObj.size(); i++) {
            const Json::Value::Members memberNames = arrayObj[i].getMemberNames();
            for(int j=0; j<memberNames.size(); j++) {
                std::cout << memberNames[j] << std::endl;
            }
        }
        //for (unsigned int i = 0; i < arrayObj.size(); i++)
        //{
        //if (!arrayObj[i].isMember("cpp"))
        //    continue;
        //out = arrayObj[i].asString();
        //std::cout << out;
        //if (i != (arrayObj.size() - 1))
        //    std::cout << std::endl;
        //std::cout << "1111" << std::endl;
        //}
    }
}
Example #17
0
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;
}
Example #18
0
    void SimplifyTags(Json::Value& target,
                      const Json::Value& source,
                      DicomToJsonFormat format)
    {
      assert(source.isObject());

      target = Json::objectValue;
      Json::Value::Members members = source.getMemberNames();

      for (size_t i = 0; i < members.size(); i++)
      {
        const Json::Value& v = source[members[i]];
        const std::string& type = v["Type"].asString();

        std::string name;
        switch (format)
        {
          case DicomToJsonFormat_Human:
            name = v["Name"].asString();
            break;

          case DicomToJsonFormat_Short:
            name = members[i];
            break;

          default:
            throw OrthancException(ErrorCode_ParameterOutOfRange);
        }

        if (type == "String")
        {
          target[name] = v["Value"].asString();
        }
        else if (type == "TooLong" ||
                 type == "Null")
        {
          target[name] = Json::nullValue;
        }
        else if (type == "Sequence")
        {
          const Json::Value& array = v["Value"];
          assert(array.isArray());

          Json::Value children = Json::arrayValue;
          for (Json::Value::ArrayIndex i = 0; i < array.size(); i++)
          {
            Json::Value c;
            SimplifyTags(c, array[i], format);
            children.append(c);
          }

          target[name] = children;
        }
        else
        {
          assert(0);
        }
      }
    }
/// 从 Json 解析数据到 dictNode 中
static void parseFromJsonToDictionary(const Json::Value & jsonNode, CCDictionary * dictNode)
{
	Json::Value::Members members = jsonNode.getMemberNames();
	for (Json::Value::Members::iterator beg = members.begin(); beg != members.end(); ++beg)
	{
        std::string name = *beg;
		Json::Value child = jsonNode[name];
		
		if (child.isArray())
		{
			CCArray * arr = CCArray::create();
			parseFromJsonToArray(child, arr);
			dictNode->setObject(arr, name);
		}
		else if (child.isObject())
		{
			CCDictionary * dict = CCDictionary::create();
			parseFromJsonToDictionary(child, dict);
			dictNode->setObject(dict, name);
		}
		else if (child.isString())
		{
			CCString * str = CCString::createWithFormat("%s", child.asCString());
			dictNode->setObject(str, name);
		}
		else if (child.isInt())
		{
			CCString * str = CCString::createWithFormat("%d", child.asInt());
			dictNode->setObject(str, name);
		}
		else if (child.isUInt())
		{
			CCString * str = CCString::createWithFormat("%u", child.asUInt());
			dictNode->setObject(str, name);
		}
		else if (child.isInt64())
		{
			CCString * str = CCString::createWithFormat("%lld", child.asInt64());
			dictNode->setObject(str, name);
			
		}
		else if (child.isUInt64())
		{
			CCString * str = CCString::createWithFormat("%llu", child.asUInt64());
			dictNode->setObject(str, name);
		}
		else if (child.isDouble())
		{
			CCString * str = CCString::createWithFormat("%f", child.asDouble());
			dictNode->setObject(str, name);
		}
		else if (child.isBool())
		{
			CCString * str = CCString::createWithFormat("%d", child.asInt());
			dictNode->setObject(str, name);
		}
	}
}
Example #20
0
void JsonTree::init( const string &key, const Json::Value &value, bool setType, NodeType nodeType, ValueType valueType )
{
    mKey = key;
	mNodeType = nodeType;
	mParent = 0;
	mValue = "";
	mValueType = valueType;

	if( ! value.isNull() && ( value.isArray() || value.isObject() ) ) {
        if( value.isArray() ) {
            mNodeType = NODE_ARRAY;
            for ( uint32_t i = 0; i < value.size(); i++ ) {
                pushBack( JsonTree( "", value[ i ] ) );
            }
        }
		else if( value.isObject() ) {
            mNodeType = NODE_OBJECT;
            Json::Value::Members members = value.getMemberNames();
            for( Json::Value::Members::const_iterator memberIt = members.begin(); memberIt != members.end(); ++memberIt ) {
				string key = *memberIt;
                pushBack( JsonTree( key, value[ key ] ) );
            }
        }
    }
	else {
		if( value.isBool() ) {
			mValue = toString( value.asBool() );
			if( setType ) {
				mValueType = VALUE_BOOL;
			}
		}
		else if ( value.isDouble() ) { 
			mValue = toString( value.asDouble() );
			if ( setType ) {
				mValueType = VALUE_DOUBLE;
			}
		}
		else if ( value.isInt() ) { 
			mValue = toString( value.asInt() );
			if ( setType ) {
				mValueType = VALUE_INT;
			}
		}
		else if ( value.isString() ) { 
			mValue = toString( value.asString() );
			if ( setType ) {
				mValueType = VALUE_STRING;
			}
		}
		else if ( value.isUInt() ) { 
			mValue = toString( value.asUInt() );
			if ( setType ) {
				mValueType = VALUE_UINT;
			}
		}
	}
}
Example #21
0
void JsonManager::initFromFile( const std::string& fileName )
{
	Json::Value json = ReadFileToJson(fileName);
	if( json.isObject() ) {
		Json::Value::Members domains = json.getMemberNames();
		for(int i=0; i< domains.size(); i++){
			m_domains[ domains[i] ] = json[domains[i]];
			CCLog("loaded json domain %s", domains[i].c_str() );
		}
	}
}
Example #22
0
void LevelsParser::parseEntity(const Json::Value& json, Entity* entity) {
  using namespace Json;
  Json::Value::Members members = json.getMemberNames();
  
  for (int i = 0; i < members.size(); ++i) {
    String member = members[i];
    shared_ptr<EntityParser> parser = EntityParser::parser(member);
    Json::Value data = json[parser->type().c_str()];
    parser->parse(entity, data);
  }
}
Example #23
0
void readJsonDict() {
    std::string strValue = "{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"}";
    Json::Reader reader;
    Json::Value value;
    reader.parse(strValue, value);
    std::cout << "value.isObject=" << value.isObject() << std::endl;
    const Json::Value::Members memberNames = value.getMemberNames();
    for(int i=0; i<memberNames.size(); i++) {
        std::cout << memberNames[i] << ":" << value[memberNames[i]] << std::endl;
    }
}
Example #24
0
	void DbgPrintValue( const Json::Value& value )
	{
		const Json::Value::Members valueMembers = value.getMemberNames();
		const UINT numMembers = valueMembers.size();
		for( UINT i = 0; i < numMembers; i++ )
		{
			const Json::Value& member = valueMembers[i];
			const std::string s = member.toStyledString();
			DBGOUT( "\t%s\n", s.c_str() );
			//DBGOUT( "\t%s\n", member.c_str() );
		}
	}
Example #25
0
configMonsterItem* CData::getConfigOfMonster(int tempid)
{
    if(m_config_monster_dic->count() < 1)
    {
        //   const char * path=FileUtils::getInstance()->fullPathForFilename("hero.json").c_str();
        //        ifstream ifs;
        //        ifs.open(path);
        //        assert(ifs.is_open());
        
        Json::Reader reader;
        Json::Value root;
        Json::Value items;
        
        Json::Value::Members members;
        
        //        Json::Value::iterator it;
        Json::Value::Members::iterator it;
        
        string path = FileUtils::getInstance()->fullPathForFilename("monster.json");
        __String* str = __String::createWithContentsOfFile(path.c_str());
        
        if(reader.parse(str->getCString(), root)){
            
            members = root.getMemberNames();
            it = members.begin();
            while (it != members.end()) {
                
                items = root[std::string(*it)];
                
                configMonsterItem * item= new configMonsterItem();
                char inttostr[20]="";
                sprintf(inttostr, "%d",tempid);
                
                
                
                item->id = items["id"].asInt();
                item->nickname = items["nickname"].asString();//" : "蛮夷邪士",
                                
                m_config_monster_dic->setObject(item, item->id);
                
                it++;
            }
            
                      
        }
        
    }
    
    
    return (configMonsterItem*)m_config_monster_dic->objectForKey(tempid);

}
Example #26
0
int loadConfig(const char* filepath, Config& config)
{
	std::ifstream confFile;
	confFile.open(filepath);
	if (!confFile.is_open())
	{
		cerr << "could not open config file: " << filepath << endl;
		return -1;
	}
	else
	{
		cout << "config file opened" << endl;
	}

	confFile.seekg(0, ios::end);
	int fileLen = confFile.tellg();
	char *confStr = NULL;
	confStr = new char[fileLen+1];
	confFile.seekg(0, ios::beg);
	confFile.get(confStr, fileLen+1);
	//confStr[fileLen] = 0;

	Json::Reader reader;
	Json::Value confRoot;

	if (!reader.parse(confStr, confRoot))
	{
		cerr << "error parsing config file: " << endl << reader.getFormattedErrorMessages() << endl;
		return -2;
	}
	else
	{
		config.com.num = confRoot["COM"]["num"].asInt();
		config.com.baud = confRoot["COM"]["baud"].asInt();
		config.sock.port = confRoot["socket"]["port"].asInt();
		config.sock.rbuff = confRoot["socket"]["read_buffer"].asInt();
		config.sock.wbuff = confRoot["socket"]["send_buffer"].asInt();

		Json::Value::Members styleNames = confRoot["style"].getMemberNames();
		for (Json::Value::Members::iterator itr = styleNames.begin(); itr != styleNames.end();itr++)
		{
			config.style.styles.insert(map<string, string>::value_type(*itr, confRoot["style"][*itr].asString()));
		}
	}
	confFile.close();
	
	delete[] confStr;
	
	return 0;
	
}
Example #27
0
Resource *ResourceManager::_load(std::string filename)
{
    Json::Reader reader(Json::Features::strictMode());

    Json::Value root;

    if (not reader.parse(readFile(filename), root))
    {
        std::cout << reader.getFormattedErrorMessages() << std::endl;
        return NULL;
    }

    std::unordered_map<std::string, ResPtr<Resource> > externalResources;

    if (root.isMember("external resources"))
    {
        Json::Value externResVal = root["external resources"];
        Json::Value::Members members = externResVal.getMemberNames();

        for (Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it)
        {
            std::string name = *it;
            ResPtr<Resource> resource = load(externResVal[name].asString());

            externalResources[name] = resource;
        }
    }

    std::string resourceType = root["type"].asString();

    if (resourceType == "texture")
    {
        return loadTexture(getMember(root, "texture"), externalResources);
    } else if (resourceType == "model")
    {
        return loadModel(getMember(root, "model"), externalResources);
    } else if (resourceType == "mesh")
    {
        return loadMesh(getMember(root, "mesh"), externalResources);
    } else if (resourceType == "shader")
    {
        return loadShader(getMember(root, "shader"), externalResources);
    } else if (resourceType == "material")
    {
        return loadMaterial(getMember(root, "material"), externalResources);
    } else
    {
        throw std::runtime_error("Unknown resource type.");
    }
}
Example #28
0
  //Load skin
  bool Skin::load(const std::string& filename) {
    std::ifstream ifs(filename);
    std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());

    Json::Value root;
    Json::Reader reader;

    m_classes.clear();

    if (!reader.parse(str, root)) {
      return false;
    }

    Json::Value::Members classes = root.getMemberNames();
    for (uint32 i = 0; i < classes.size(); i++) {
      std::string name = classes[i];
      Json::Value v = root[name];

      Skin::SkinClass sc;

      bool addP = false;

      //We need to figure out if we're dealing with sub classes.
      Json::Value::Members subs = v.getMemberNames();
      for (uint32 j = 0; j < subs.size(); j++) {
        if (subs[j] != "normal" && subs[j] != "hover" && subs[j] != "active" && subs[j] != "focus") {
          //Yup, this is a sub class.
          Skin::SkinClass sub;
          jsonToStates(v[subs[j]], sub);

          sc.m_subs.insert(ClassMapPair(subs[j], sub));

        } else {
          addP = true;
        }
      }

      //There's a valid state in the root
      if (addP) {
        jsonToStates(v, sc);
      }

      sc.reset();
      m_classes.insert(ClassMapPair(name, sc));
    }

    m_loaded = filename;

    return true;
  }
Example #29
0
void SceneObject::initWith(Json::Value _val) 
{
	Json::Value::Members mems = _val.getMemberNames();
	Json::Value::Members::iterator mit;
	for (mit = mems.begin(); mit != mems.end(); mit++) {
		if ((*mit) == "Name") {
			m_Name = _val["Name"].asString();
		}else{
			if (Component_maker::ComponentExists((*mit))) {
				addComponent(Component_maker::makeComponent((*mit), this));
				m_Components[(*mit)]->initWith(_val[(*mit)]);
			}
		}
	}
}
Example #30
0
bool OnlineProcess::init() {
    
    bool ret = parseJson(fileName_, configs_);
    if( !ret ) {
        std::cout<< "error in parse json" <<std::endl;
        return false;
    }
    sourceDir_ = "../source";
    if ( configs_["source_dir"].isString() ) {  
        sourceDir_ = configs_["source_dir"].asString();
    }
    
    ret = initResource();
    if( !ret ) {
        std::cout<<"init resource error " <<std::endl;
        return false;
    }
    //useLocalIdf_ = configs_["use_local_idf"].asBool();
    
	wordSplitDicVec_.clear();
    size_t size = configs_["wordsplit_dic"].size();
    for(size_t i=0 ; i<size ; i++ ){
        std::string name = sourceDir_ +"/" + configs_["wordsplit_dic"][i].asString();
        wordSplitDicVec_.push_back(name);
    }
    
	Tools& tools_  = ProcessResource::instance().tools() ;
	int result = tools_.m_wordsplit->load(wordSplitDicVec_);
    if ( result != 0 ) {
        std::cout<<"init wordsplit error" <<std::endl;
        return false;
    }
    
    Json::Value& strategy = configs_["strategy"];
    Json::Value::Members members = strategy.getMemberNames();
    Json::Value::Members::iterator iter  = members.begin();
    for( ;iter != members.end(); iter++ ) {
        std::string name  = *iter; 
        std::string ruleFile = strategy[name].asString();
        ProcessStrategy& ps = strategies_[name];
        ret = ps.init(ruleFile, *this);
        if( !ret ) {
            std::cout<<" init failed: "<< name <<std::endl;
            return false;
        }
    }
    return true;
}