std::string RechargeRequestData::encode(bool readable)
{
    Json::Value root = encode_to_json_object();
    if ( readable )
    {
        Json::StyledWriter writer;
        return writer.write(root);
    }
    else
    {
        Json::FastWriter writer;
        return writer.write(root);
    }
}
std::string CheckUserNameRequest::encode(bool readable)
{
    Json::Value root = encode_to_json_object();
    if ( readable )
    {
        Json::StyledWriter writer;
        return writer.write(root);
    }
    else
    {
        Json::FastWriter writer;
        return writer.write(root);
    }
}
Esempio n. 3
0
 string JobCodec::encode(const Job& job)
 {
     Json::Value root;
     Json::StyledWriter writer;
     
     root["uid"] = job.uid();
     root["data"] = job.data();
     root["status"] = job.status();
     root["status_description"] = job.status_description();
     root["run_at"] = (int)job.run_at();
     root["timestamp"] = (int)job.timestamp();
     
     return writer.write(root);
 }
Esempio n. 4
0
int main(int argc, char** argv)
{ 
// ---- create from scratch ----

Json::Value fromScratch;
Json::Value array;
array.append("hello");
array.append("world");
fromScratch["hello"] = "world";
fromScratch["number"] = 2;
fromScratch["array"] = array;
fromScratch["object"]["hello"] = "world";

output(fromScratch);

// write in a nice readible way
Json::StyledWriter styledWriter;
std::cout << styledWriter.write(fromScratch);

// ---- parse from string ----

// write in a compact way
Json::FastWriter fastWriter;
std::string jsonMessage = fastWriter.write(fromScratch);

Json::Value parsedFromString;
Json::Reader reader;
bool parsingSuccessful = reader.parse(jsonMessage, parsedFromString);
if (parsingSuccessful)
{
    std::cout << styledWriter.write(parsedFromString) << std::endl;
}



  return 0;
}
BOOL SessionLayout::_displayMsgToIE(IN MessageEntity msg ,IN CString jsInterface)
{
	module::UserInfoEntity userInfo;
	if (!module::getUserListModule()->getUserInfoBySId(msg.talkerSid, userInfo))
	{
		return FALSE;
	}

	Json::Value root;
	root["name"] = util::cStringToString(userInfo.getRealName());
	root["avatar"] = userInfo.getAvatarPathWithoutOnlineState();
	root["msgtype"] = msg.msgRenderType;
	root["uuid"] = msg.talkerSid;
	CString csContent = util::stringToCString(msg.content);
	ReceiveMsgManage::getInstance()->parseContent(csContent, FALSE, GetWidth(), !msg.isMySendMsg());
	root["content"] = util::cStringToString(csContent);
	if (msg.isMySendMsg())
	{
		root["mtype"] = "me";
	}
	else
	{
		root["mtype"] = "other";
	}
	CTime timeData(msg.msgTime);
	root["time"] = util::cStringToString(timeData.Format(_T("%Y-%m-%d %H:%M:%S")));
	Json::StyledWriter styleWrite;
	std::string record = styleWrite.write(root);
	Json::Reader jsonRead;
	Json::Value rootRead;
	CString jsData = _T("[]");
	if (!jsonRead.parse(record, rootRead) || rootRead.isNull())
	{
		CString csError = util::stringToCString(record, CP_UTF8);
		APP_LOG(LOG_INFO, TRUE, _T("json parse error:%s"), csError);
		jsData = _T("[]");
		return FALSE;
	}
	else
		jsData = util::stringToCString(record, CP_UTF8);
	//调用页面的JS代码
	if (m_pWebBrowser)
	{
		VARIANT VarResult;
		m_pWebBrowser->CallJScript(jsInterface.GetBuffer(), jsData.GetBuffer(), &VarResult);
		jsData.ReleaseBuffer();
	}
	return TRUE;
}
/**
 * @brief Serialize to JSON object
 * @return JSON object as std::string
 */
std::string PeakShapeSpherical::toJSON() const {
  Json::Value root;
  PeakShapeBase::buildCommon(root);
  root["radius"] = Json::Value(m_radius);

  if (m_backgroundInnerRadius && m_backgroundOuterRadius) {
    root["background_outer_radius"] =
        Json::Value(m_backgroundOuterRadius.get());
    root["background_inner_radius"] =
        Json::Value(m_backgroundInnerRadius.get());
  }

  Json::StyledWriter writer;
  return writer.write(root);
}
Esempio n. 7
0
void enviarNivel(Socket& sockfd, nivel_t& nivel, string* creador = NULL, int jugadores = 0){
    Json::Value mensaje;
    Json::StyledWriter escritor;

    mensaje["tipo"] = (creador == NULL) ? INFO_CREAR : INFO_UNIRSE;
    mensaje["nombre"] = *(nivel.nombre);
    mensaje["creador"] = (creador == NULL) ? "" : *creador;
    mensaje["puntaje"] = htonl((uint32_t) nivel.puntaje);
    mensaje["max jugadores"] = htonl((uint32_t) nivel.cant_jugadores_max);
    mensaje["jugadores"] = htonl((uint32_t) jugadores);
    std::cout<<mensaje;
    std::string envio = escritor.write(mensaje);

    enviarMsjPrefijo(sockfd, envio.c_str(), envio.length());
}
Esempio n. 8
0
void RtcStream::OnIceCandidate(const webrtc::IceCandidateInterface* candidate) {
    std::string cand;
    if (!candidate->ToString(&cand)) {
        LOG(LS_ERROR) << "Failed to serialize candidate";
        return;
    }

    Json::StyledWriter writer;
    Json::Value jmessage;
    jmessage[kCandidateSdpMidName] = candidate->sdp_mid();
    jmessage[kCandidateSdpMlineIndexName] = candidate->sdp_mline_index();
    jmessage[kCandidateSdpName] = cand;
    std::string encodedCand = talk_base::Base64::Encode( writer.write(jmessage));
    SignalIceCandidate(this, encodedCand);
}
Esempio n. 9
0
string  BatchCall::toString     (bool fast) const
{
    string result;
    if (fast)
    {
        Json::FastWriter writer;
        result = writer.write(this->result);
    }
    else
    {
        Json::StyledWriter writer;
        result = writer.write(this->result);
    }
    return result;
}
QString JsonFormatter::getFormatted()
{
	Json::Value root;   
	Json::Reader reader;
	bool parsingSuccessful = reader.parse( rawValue.toStdString(), root );

	if (!parsingSuccessful)
	{
		return QString("Invalid JSON");
	}

	Json::StyledWriter writer;		

	return QString::fromStdString(writer.write(root));
}
Esempio n. 11
0
std::string MalwrDTO::toJSON(){
    Json::Value root;
    root["md 5"] = md5;
    root["fileName"] = fileName;
    root["fileType"] = fileType;
    root["antivirusScore"] = antivirusScore;
    root["link"] = link;
    root["date"] = date;

    Json::StyledWriter writer;
    std::string outputConfig = writer.write( root );
//    std::cout << outputConfig << std::endl;

    return outputConfig;
}
Esempio n. 12
0
static int rewriteValueTree(const std::string& rewritePath,
                            const Json::Value& root,
                            std::string& rewrite) {
  // Json::FastWriter writer;
  // writer.enableYAMLCompatibility();
  Json::StyledWriter writer;
  rewrite = writer.write(root);
  FILE* fout = fopen(rewritePath.c_str(), "wt");
  if (!fout) {
    printf("Failed to create rewrite file: %s\n", rewritePath.c_str());
    return 2;
  }
  fprintf(fout, "%s\n", rewrite.c_str());
  fclose(fout);
  return 0;
}
std::string MetaRequestHandler::constructResponse() {
  const auto &storageManager = StorageManager::getInstance();
  Json::Value result;
  auto &tables = result["tables"];
  for (const auto & tableName: storageManager->getTableNames()) {
    auto &table = tables[tableName];
    auto &columns = table["columns"];
    auto t = storageManager->getTable(tableName);
    table["columnCount"] = t->columnCount();
    for (field_t i = 0; i != t->columnCount(); i++) {
      columns[t->metadataAt(i)->getName()] = t->metadataAt(i)->getType();
    }
  }
  Json::StyledWriter writer;
  return writer.write(result);
}
Esempio n. 14
0
string JsonTransf::JsonCppToString(Json::Value& jsonValue, const bool bStyled)
{
	string str; 
	if(bStyled)
	{
		Json::StyledWriter writer;
		str = writer.write(jsonValue);
	}
	else
	{
		Json::FastWriter writer;
		str = writer.write(jsonValue);
		str.erase(str.length()-1, 1);
	}
	return str;
}
Esempio n. 15
0
bool write_user_db(Json::Value *root, const std::string &dbpath)
{
    Json::StyledWriter writer;
    std::ofstream userdb_file;
    std::string userdb_json = writer.write(*root);

    userdb_file.open(dbpath,std::ofstream::trunc);
    if (!userdb_file.is_open())
        return false;

    userdb_file << userdb_json;
    userdb_file.close();

    return true;
    
}
Esempio n. 16
0
void MapController::saveMap() {

	Json::Value root;

	std::stringstream ss;
	ss << std::hex << this->map->getSeed();
	root["seed"] = ss.str();

	for (int k = 0; k < turnController->playerList.size(); k++) {
		if (turnController->playerList[k] == turnController->getActivePlayer())
		{
			root["turn"] = k;
		}
	}

	Json::Value countryList;

	for (int i = 0; i < this->map->getNumCountries(); i++)
	{
		Json::Value country;
		for (int k = 0; k < turnController->playerList.size(); k++)
		{
			if (std::find(turnController->playerList[k]->countries.begin(), turnController->playerList[k]->countries.end(), this->map->getCountryById(i)) != turnController->playerList[k]->countries.end())
			{
				country["owner"] = k + 1;
				break;
			}
			else
			{
				country["owner"] = 0;
			}
		}

		country["units"] = this->map->getCountryById(i)->getUnits();
		countryList.append(country);
	}

	root["countries"] = countryList;

    Json::StyledWriter writer;

    std::ofstream myfile;
    myfile.open ("savedConfig.json");
    myfile << writer.write(root);

    myfile.close();
}
Esempio n. 17
0
void CWebRTCAPI::SendWindowHandle(HWND wnd) {
	LOG(INFO) << __FUNCTION__;
	ASSERT(wnd != NULL);
	uint32_t wndPtr = reinterpret_cast<uint32_t>(wnd);

	Json::StyledWriter writer;
	Json::Value json;
	Json::Value pluginMessage;

	pluginMessage["data"] = wndPtr;
	pluginMessage["message"] = "gotWindowHandle";
	json["pluginMessage"] = pluginMessage;

	//std::string* str = new std::string(writer.write(json));

	SendToBrowser(writer.write(json) /* *str */);
}
Esempio n. 18
0
key::JsonConfig::JsonConfig(std::string main_config_filename) : configuration_is_valid(false) {
	bool could_read = false;
	
	std::string full_config_filename = fullPathTo(main_config_filename);

	if (!stringFromFile(main_configuration_contents, full_config_filename)) {
		Json::Value root;
		root["js_root_dir"] = "js";
		root["js_main_file"] = "main.js";

		Json::StyledWriter writer;
		main_configuration_contents = writer.write( root );

		ofstream out(full_config_filename, ios::out | ios::binary);
		if (!out) {
			cout << "Cannot write default config to \"" << full_config_filename << "\"." << endl;
		} else {
			out << main_configuration_contents;
			out.close();
			could_read = true;
		}
	} else {
		could_read = true;
	}

	if (could_read) {
		Json::Value root;
		Json::Reader reader;

		if (!reader.parse(main_configuration_contents, root))
		{
			cout << "could not PARSE configuration file!" << endl; 
			cout << reader.getFormatedErrorMessages() << endl;
		} 
		else 
		{
			// read config
			js_root_dir = root.get("js_root_dir", "js").asString();
			js_main_file = root.get("js_main_file", "main.js").asString();

			configuration_is_valid = true;
		}
	} else {
		std::cout << "Failed to read configuration from \"" << fullPathTo(main_config_filename) << "\"." << std::endl;
	}
}
Esempio n. 19
0
bool KeTunnelClient::SendCommand(const std::string &peer_id,
                                 const std::string &command)
{
    Json::Reader reader;
    Json::Value jmessage;
    if (!reader.parse(command, jmessage)) {
        LOG(WARNING) <<"command format error. " << command;
        return false;
    }
    jmessage[kKaerMsgTypeName] = kKaerTunnelMsgTypeValue;

    Json::StyledWriter writer;
    std::string msg = writer.write(jmessage);

    return this->terminal_->SendByRouter(peer_id,msg);
    return true;
}
Esempio n. 20
0
int HttpWGReader::ReadSearchPlayers(LPSTR str, char nick[NICKLENGTH])
{
	Json::Value root;
	Json::StyledWriter styledWriter;
	Json::Reader reader;

	LPCWSTR lpcwDesignString;
	std::wstring ws;
	std::string status;

	CHAR lpId[10]; // ID игрока
	_itoa_s(HttpWGReader::GetPlayerID(), lpId, 10, 10);

	CHAR tmp[124];

	// Парсинг строки
	BOOL parsingSuccessful = reader.parse(str, root);
	if (parsingSuccessful)
	{
		string_to_wstring(styledWriter.write(root), ws);
		lpcwDesignString = ws.c_str();
		OutputDebugString(lpcwDesignString);
	}
	else
	{
		OutputDebugStringA("Parsing ReadSearchPlayers error!!!");
		return -1;
	}

	// Проверяем правильное сообщение или считывание
	status = root.get("status", "error").asString();
	if (strcmp(status.c_str(), "ok"))
	{
		OutputDebugStringA("\n\nParsing Status ReadPersonalPlayerData error!!!\n\n");
		return -1;
	}

	const Json::Value data = root["data"];

	for (int i = 0; i < data.size(); i++)
	{
		if (!strcmp(data[i]["nickname"].asString().c_str(), nick))
			return atoi(data[i]["account_id"].asString().c_str());
		else return -1;
	}
}
Esempio n. 21
0
PVR_ERROR cPVRClientForTheRecord::DeleteRecording(const PVR_RECORDING &recinfo)
{
  // JSONify the stream_url
  Json::Value recordingname (recinfo.strStreamURL);
  Json::StyledWriter writer;
  std::string jsonval = writer.write(recordingname);
  if (ForTheRecord::DeleteRecording(jsonval) >= 0) 
  {
    // Trigger XBMC to update it's list
    PVR->TriggerRecordingUpdate();
    return PVR_ERROR_NO_ERROR;
  }
  else
  {
    return PVR_ERROR_NOT_DELETED;
  }
}
void writeJson(const string& jsonName, const SimpleSurveyParameters& params)
{
  Json::Value root;
  params >>= root;

  ofstream jsonStream(jsonName.c_str());
  if (!jsonStream) {
    cerr << "couldn't open " << jsonName << " for writing: " << strerror(errno) << endl;
    exit(1);
  }

  Json::StyledWriter writer;
  jsonStream << writer.write(root);
  jsonStream.close();

  cout << "wrote output to " << jsonName << endl;
}
Esempio n. 23
0
		//----------
		void Serializable::save(string filename) {
			if (filename == "") {
				auto result = ofSystemSaveDialog(this->getDefaultFilename(), "Save " + this->getTypeName());
				if (result.bSuccess) {
					filename = result.fileName;
				}
			}

			if (filename != "") {
				Json::Value json;
				this->serialize(json);
				Json::StyledWriter writer;
				ofFile output;
				output.open(filename, ofFile::WriteOnly, false);
				output << writer.write(json);
			}
		}
Esempio n. 24
0
  /**
   * \brief AreRecordingSharesAccessible
   * \param thisplugin the plugin to check
   * \param response Reference to a std::string used to store the json response string
   * \return  0 when successful
   */
  int AreRecordingSharesAccessible(Json::Value& thisplugin, Json::Value& response)
  {
    XBMC->Log(LOG_DEBUG, "AreRecordingSharesAccessible");
    Json::StyledWriter writer;
    std::string arguments = writer.write(thisplugin);

    int retval = ForTheRecordJSONRPC("ForTheRecord/Control/AreRecordingSharesAccessible", arguments, response);

    if (response.type() != Json::arrayValue)
    {
      // response on error is a objectValue
      // TODO: parse it to display the error
      return -1;
    }

    return retval;
  }
std::string HoarStoneManager::convertDataToJson()
{
	Json::Value root;
	
	for(List<HoarStoneData>::Iter * hoarStoneIter = m_pHoarStoneList->begin(); hoarStoneIter != NULL; 
		hoarStoneIter = m_pHoarStoneList->next(hoarStoneIter))
	{
		Json::Value hoarStoneRoot;
		hoarStoneRoot["level"] = hoarStoneIter->mValue.mStoneLv;
		hoarStoneRoot["piece"] = hoarStoneIter->mValue.mPieceCount;
		hoarStoneRoot["star"] = hoarStoneIter->mValue.mStoneStar;

		for(List<UInt64>::Iter * equipIter = hoarStoneIter->mValue.mEquipList.begin(); equipIter != NULL; 
			equipIter = hoarStoneIter->mValue.mEquipList.next(equipIter))
		{
			hoarStoneRoot["equip"].append(equipIter->mValue);
		}

		root["base"].append(hoarStoneRoot);

	}


	std::stringstream mystream;

	for(RuneDataMap::Iter*  runeIter = m_pRuneDataMap->begin(); runeIter != NULL; runeIter = m_pRuneDataMap->next(runeIter))
	{
		mystream.clear();
		mystream.str("");

		mystream << runeIter->mKey;
		std::string runeKeyStr;
		mystream >> runeKeyStr; 

		root["equip"][runeKeyStr] = runeIter->mValue;
	}


	Json::StyledWriter writer;

	std::string jsonStr = writer.write(root);

	//cout << jsonStr;

	return jsonStr;
}
Esempio n. 26
0
 void Serializer::saveComponentState(const std::list<Component::Ptr> &theComponentList,
                                     const std::string &theFileName,
                                     const PropertyIO &theIO)
 {
     Json::Value myRoot;
     add_to_json_object(theComponentList, myRoot, theIO);
     Json::StyledWriter myWriter;
     std::string state = myWriter.write(myRoot);
     
     std::ofstream myFileOut(theFileName.c_str());
     if(!myFileOut)
     {
         throw OutputFileException(theFileName);
     }
     myFileOut << state;
     myFileOut.close();
 }
Esempio n. 27
0
 void sendTun(const char *_msg, std::shared_ptr<TunDevice> tun,
              std::shared_ptr<typename WsServer::Connection> connection) {
   auto send_stream = std::make_shared<typename WsServer::SendStream>();
   MessageRef<TunDevice> msg(_msg, *tun);
   Json::Value out;
   msg.asJson(out);
   Json::StyledWriter styledWriter;
   *send_stream << "JSON";
   *send_stream << styledWriter.write(out);
   wsServer->send(connection, send_stream,
                  [msg](const boost::system::error_code &ec) {
                    if (ec) {
                      LOG(ERROR) << "Server: Error sending tun-message:" << msg.getAction()
                         << ":" << ec << ", error message: " << ec.message();
                    }
                  });
 }
Esempio n. 28
0
bool ccIoTDeviceProtocol::Send(ccWebsocket* oWS, bool bIsRequest, const std::string& strCommand, const Json::Value& oExtInfo)
{
    std::string strData;

    Json::Value oProtocol;
    Json::StyledWriter oWriter;

    oProtocol["Request"] = bIsRequest;
    oProtocol["Command"] = strCommand;

    if (!oExtInfo.isNull())
        oProtocol["Info"] = oExtInfo;

    strData = std::move(oWriter.write(oProtocol));

    return oWS->Send(strData);
}
Esempio n. 29
0
void BigPotConfig::write()
{
#ifdef USINGJSON
	Json::StyledWriter writer;

	_value["record"] = _record;
	_content = writer.write(_value);

	ofstream ofs;
	ofs.open(_filename);
	ofs << _content;
#else
	//_doc.LinkEndChild(_doc.NewDeclaration());
	_doc.LinkEndChild(_root);
	_doc.SaveFile(_filename.c_str());
#endif
}
Esempio n. 30
0
void CPlayerGameData::TimerSave()
{
	for ( uint8_t nIdx = eRoom_None; nIdx < eRoom_Max ; ++nIdx )
	{
		auto& gameData = m_vData[nIdx] ;
		if ( gameData.bDirty == false )
		{
			continue;
		}

		gameData.bDirty = false ;

		Json::Value jsValue ;
		jsValue["gameType"] = nIdx ;

		Json::Value jsData ;
		jsData["nWinTimes"] = gameData.nWinTimes ;
		jsData["nChampionTimes"] = gameData.nChampionTimes ;
		jsData["nPlayTimes"] = gameData.nPlayTimes ;
		jsData["nRun_upTimes"] = gameData.nRun_upTimes ;
		jsData["nSingleWinMost"] = (uint32_t)gameData.nSingleWinMost ;
		jsData["nThird_placeTimes"] = gameData.nThird_placeTimes ;

		Json::Value jsMaxCard ;
		for ( uint8_t nCardIdx = 0 ; nCardIdx < MAX_TAXAS_HOLD_CARD ; ++nCardIdx ) 
		{
			jsMaxCard[nCardIdx] = gameData.vMaxCards[nCardIdx] ;
		}
		jsData["vMaxCards"] = jsMaxCard ;
		jsValue["data"] = jsData ;

		Json::StyledWriter jsWrite ;
		std::string str = jsWrite.write(jsValue) ;

		stMsgSavePlayerGameData msgSave ;
		msgSave.nGameType = nIdx ;
		msgSave.nUserUID = GetPlayer()->GetUserUID() ;
		msgSave.nJsonLen = str.size() ;
		CAutoBuffer auBuffer ( sizeof(msgSave) + msgSave.nJsonLen );
		
		auBuffer.addContent(&msgSave,sizeof(msgSave)) ;
		auBuffer.addContent(str.c_str(),msgSave.nJsonLen) ;
		SendMsg((stMsg*)auBuffer.getBufferPtr(),auBuffer.getContentSize()) ;
	}
}