void ttt::JSONTissueTrackingProject::StoreFrameInfo(){


	Json::Value root;
	Json::StyledWriter writer;

	root["platenessSteps"]=this->m_PlatenessSteps;
	root["platenessHighestScale"]=this->m_HighestPlatenessScale;
	root["platenessLowestScale"]=this->m_LowestPlatenessScale;

	root["vertexnessSteps"]=this->m_VertexnessSteps;
	root["vertexnessHighestScale"]=this->m_HighestVertexnessScale;
	root["vertexnessLowestScale"]=this->m_LowestVertexnessScale;

	std::stringstream fileNameStream;
	fileNameStream << m_ProjectPath << "/" << "frame-"<< m_Frame << ".json";
	std::string projectConfigFile;
	fileNameStream >> projectConfigFile;

	std::string jsoncontent=writer.write(root);
	std::ofstream file (projectConfigFile.c_str(), std::ofstream::out | std::ofstream::trunc);

	file << jsoncontent;

	file.close();

}
Esempio n. 2
0
// write_json(data[, styled]) -> string or nil and error message
int ModApiUtil::l_write_json(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	bool styled = false;
	if (!lua_isnone(L, 2)) {
		styled = lua_toboolean(L, 2);
		lua_pop(L, 1);
	}

	Json::Value root;
	try {
		read_json_value(L, root, 1);
	} catch (SerializationError &e) {
		lua_pushnil(L);
		lua_pushstring(L, e.what());
		return 2;
	}

	std::string out;
	if (styled) {
		Json::StyledWriter writer;
		out = writer.write(root);
	} else {
		Json::FastWriter writer;
		out = writer.write(root);
	}
	lua_pushlstring(L, out.c_str(), out.size());
	return 1;
}
Esempio n. 3
0
//////////////////////////////////////////////////////////////////////////
// saveDependancy
void CsCore::saveDependancies( const BcPath& FileName )
{
	BcPath DependanciesFileName( FileName );
	
	// Append new extension.
	DependanciesFileName.append( ".dep" );
	
	// 
	Json::Value Object( Json::arrayValue );

	if( DependancyMap_.find( *FileName ) != DependancyMap_.end() )
	{
		CsDependancyList& DependancyList = DependancyMap_[ *FileName ];
	
		for( CsDependancyListIterator It( DependancyList.begin() ); It != DependancyList.end(); ++It )
		{
			Object.append( saveDependancy( (*It) ) );
		}
	}

	// Output using styled writer.
	Json::StyledWriter Writer;
	std::string JsonOutput = Writer.write( Object );

	BcFile OutFile;
	if( OutFile.open( (*DependanciesFileName).c_str(), bcFM_WRITE ) )
	{
		OutFile.write( JsonOutput.c_str(), JsonOutput.size() );
		OutFile.close();
	}
}
Esempio n. 4
0
  bool KeepLiveStreamAlive()
  {
    //Example request:
    //{"CardId":"String content","Channel":{"BroadcastStart":"String content","BroadcastStop":"String content","ChannelId":"1627aea5-8e0a-4371-9022-9b504344e724","ChannelType":0,"DefaultPostRecordSeconds":2147483647,"DefaultPreRecordSeconds":2147483647,"DisplayName":"String content","GuideChannelId":"1627aea5-8e0a-4371-9022-9b504344e724","LogicalChannelNumber":2147483647,"Sequence":2147483647,"Version":2147483647,"VisibleInGuide":true},"RecorderTunerId":"1627aea5-8e0a-4371-9022-9b504344e724","RtspUrl":"String content","StreamLastAliveTime":"\/Date(928142400000+0200)\/","StreamStartedTime":"\/Date(928142400000+0200)\/","TimeshiftFile":"String content"}
    //Example response:
    //true
    if(!g_current_livestream.empty())
    {
      Json::StyledWriter writer;
      std::string arguments = writer.write(g_current_livestream);

      Json::Value response;
      int retval = ForTheRecordJSONRPC("ForTheRecord/Control/KeepLiveStreamAlive", arguments, response);

      if (retval != E_FAILED)
      {
        //if (response == "true")
        //{
        return true;
        //}
      }
    }

    return false;
  }
Esempio n. 5
0
bool CExtInstaller::GenerateNativeAppConfig()
{
	/*
	{
	"name": "com.baidu.antivirus",
	"description": "Chrome Native Messaging API Baidu AntiVirus Host",
	"path": "exe path",
	"type": "stdio",
	"allowed_origins": [
	"chrome-extension://afbbkciigbkkonnbcagfkobemjhehfem/"
	]
	}
	*/

	Json::Value root;

	root["name"] = Json::Value(CHROME_SAMPLE_NATIVE_HOST_NAME);
	root["description"] = Json::Value("Chrome Native Messaging API Baidu AntiVirus Host");
	std::string nativeAppPath = WtoA(m_CurrentDir +_T("\\") +NAPP_PATH);
	root["path"] = Json::Value(nativeAppPath);
	root["type"] = Json::Value("stdio");
	std::string allowed_origins = "chrome-extension://";
	allowed_origins.append(CHROME_SAMPLE_CRX_ID_A);
	allowed_origins.append("/");
	root["allowed_origins"].append(allowed_origins);
	Json::StyledWriter fw;
	std::string szOssNativeAppConfig = fw.write(root);
	std::ofstream out(GetNativeAppConfigPath().c_str());
	out<<szOssNativeAppConfig;
	out.close();
	return true;
Esempio n. 6
0
void JsonTree::write( DataTargetRef target, bool createDocument )
{
	// Declare output string
	string jsonString = "";

	try {
		
		// Create JsonCpp data to send to parser
		Json::Value value = createNativeDoc( createDocument );

		// This routine serializes JsonCpp data and formats it
		Json::StyledWriter writer;
		jsonString = writer.write( value.toStyledString() );
		boost::replace_all( jsonString, "\\n", "\r\n" );
		boost::replace_all( jsonString, "\\\"", "\"" );
		if( jsonString.length() >= 3 ) {
			jsonString = jsonString.substr( 1, boost::trim_copy( jsonString ).length() - 2 );
		}
		jsonString += "\0";
	}
	catch ( ... ) {
		throw ExcJsonParserError( "Unable to serialize JsonTree." );
	}

	// Save data to file
	OStreamRef os = target->getStream();
	os->writeData( jsonString.c_str(), jsonString.length() );
}
Esempio n. 7
0
int main() {

	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;
	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)
	{
		cout << styledWriter.write(parsedFromString) << endl;
	}

	cin.ignore(1);
	return 0;
}
Esempio n. 8
0
bool JsonSerializer::serialize(JsonSerializable *pObj, std::string &output)
{
/*  if(pObj==NULL)
	return false;
  Json::Value serializeRoot;
  pObj->serialize(serializeRoot);

  Json::StyledWriter writer;
  output = writer.write(serializeRoot);
  return true;
*/
  if(pObj==NULL)
        return false;
  // treat pObj as an array
  Json::ValueType vt = Json::arrayValue;
  Json::Value serializeArrayRoot(vt);

  Json::Value serializeRoot;
  int num_of_elements = sizeof(pObj)/sizeof(JsonSerializable);
  for(int i=0; i<num_of_elements; i++)
  {
        (pObj[i]).serialize(serializeRoot);
        serializeArrayRoot[i] = serializeRoot;
  }

  Json::StyledWriter writer;
  output = writer.write(serializeArrayRoot);
  return true;

}
Esempio n. 9
0
//Callback for profile created on the other side; notification about seat state
void CStateUpdater::incomingNotification(Json::Value seatState)
{ 
    Json::StyledWriter writer;
    std::string deserializedJson = writer.write(seatState);
    LOG4CPLUS_INFO(mLogger, "The following state came: "+deserializedJson); 
    //updating GUI according to the new state 
    emit showSeat();
    int status = seatState.get("currSeat", 0).asInt();
    if (status == 0)
    {
        LOG4CPLUS_INFO(mLogger, "Currently displayed seat is Driver's seat"); 
        emit current_seat_viewDriver();
    }
    else
    {
        LOG4CPLUS_INFO(mLogger, "Currently displayed seat is Passenger's seat"); 
        emit current_seat_viewPass();
    }
    status = seatState.get("heaterDriver", 0).asInt();
    emit heaterDriver(status);
    status = seatState.get("heaterPass", 0).asInt();
    emit heaterPass(status);
    status = seatState.get("bottom_x", 0).asInt();
    emit bottom_x(status);
    status = seatState.get("bottom_y", 0).asInt();
    emit bottom_y(status);
    status = seatState.get("back_x", 0).asInt();
    emit back_x(status);
    status = seatState.get("back_y", 0).asInt();
    emit back_y(status);
    status = seatState.get("back_angle", 0).asInt();
    emit back_angle(status);
}
Esempio n. 10
0
int UnitTestJsonCpp::Run(void)
{
	Json::Value root;
	Json::Value arrayObj;
	Json::Value item;

	for (int i = 0; i < 10; i ++)
	{
		item["key"] = i;
		arrayObj.append(item);
	}

	root["key1"] = "value1";
	root["key2"] = "value2";
	root["array"] = arrayObj;
	std::string out = root.toStyledString();
	std::cout << out << std::endl;


	Json::StyledWriter writer;   
	std::string output = writer.write(root);

	std::ofstream out_file("duplicate_config.json" );   
	out_file << output;
	out_file.flush();

	return 0;
}
Esempio n. 11
0
  bool	Config::addUser(int32_t id, uint32_t token)
  {
    std::ofstream	file("conf/users.json");
    Json::Value		newUser(Json::objectValue);
    Json::StyledWriter	writer;
    Json::Value::UInt	i = _root["users"].size();

    if (!file.fail())
      {
    	if ((newUser["id"] = id) == Json::nullValue)
    	  return (false);
    	if ((newUser["token"] = token) == Json::nullValue)
    	  return (false);
    	if ((_root["users"][i] = newUser) == Json::nullValue)
    	  return (false);
    	file << writer.write(_root);
    	file.close();
    	return (true);
      }
    else
      {
    	std::cerr << "can't open the file" << std::endl;
    	return (false);
      }
  }
Esempio n. 12
0
  void RestApiOutput::AnswerJson(const Json::Value& value)
  {
    CheckStatus();

    if (convertJsonToXml_)
    {
#if ORTHANC_PUGIXML_ENABLED == 1
      std::string s;
      Toolbox::JsonToXml(s, value);
      output_.SetContentType("application/xml");
      output_.Answer(s);
#else
      LOG(ERROR) << "Orthanc was compiled without XML support";
      throw OrthancException(ErrorCode_InternalError);
#endif
    }
    else
    {
      Json::StyledWriter writer;
      output_.SetContentType("application/json");
      output_.Answer(writer.write(value));
    }

    alreadySent_ = true;
  }
Esempio n. 13
0
bool StructuredSVM::Save(const char *fname, bool saveFull, bool getLock) {
  if(getLock) Lock();
  Json::Value root;
  if(modelfile) free(modelfile);
  modelfile = StringCopy(fname);
  if(sum_w) root["Sum w"] = sum_w->save();
  root["Regularization (C)"] = params.C;
  root["Training accuracy (epsilon)"] = params.eps;
  root["T"] = (int)t;
  if(trainfile) root["Training Set"] = trainfile;
  root["Custom"] = Save();
  if(saveFull) {
    char full_name[1000];
    sprintf(full_name, "%s.online", fname);
    root["Online Data"] = full_name;
    if(!SaveOnlineData(full_name)) { Unlock(); return false; }
  }

  Json::StyledWriter writer;
  FILE *fout = fopen(fname, "w");
  if(!fout) { fprintf(stderr, "Couldn't open %s for writing\n", fname); Unlock(); return false; }
  fprintf(fout, "%s", writer.write(root).c_str());
  fclose(fout);
  if(getLock) Unlock();

  return true;
}
Esempio n. 14
0
void SignalingWebSocketPeer::sendLocalSDP(std::string type, std::string sdp) {
	Json::StyledWriter writer;
	Json::Value message;

	message["type"] = type;

	if(sdp.length() > 800) {
		for(int i=0; i<sdp.length(); i+=800) {
			int n = MIN(sdp.length()-i+1,800);
			message["sdpPartial"] = sdp.substr(i, n);

			std::string msg = writer.write(message);
			send(msg.c_str());
		}
		message.removeMember("sdpPartial");
		message["endSdp"] = "yes";
		std::string msg = writer.write(message);
		send(msg.c_str());
	}
	else {
		message["sdp"] = sdp;
		std::string msg = writer.write(message);
		send(msg.c_str());
	}
}
Esempio n. 15
0
CTrustListError CFileStorage::readAll(tUidVector& uids)
{
   LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__);
   // if (!isReady())
   //    return CTrustListError(CTrustListError::ERROR_STORAGE, gsModuleName, "file is not ready");

   Json::Value root;
   if (!reopen(ios::in) || !read(file, root))
      return CTrustListError(CTrustListError::ERROR_STORAGE, gsModuleName, "unable to parse file");

   Json::StyledWriter writer;
   std::string val = writer.write(root);
   LOG4CPLUS_INFO(msLogger, "Read all trust list: " + val);

   const Json::Value trusted = root[gsTrustedTag];
   if (trusted.isNull())
      return CTrustListError::NoTLError(gsModuleName);;

   for (size_t i = 0; i < trusted.size(); ++i)
   {
      uids.push_back(trusted[i].asString());
   }

   return CTrustListError::NoTLError(gsModuleName);;
}
Esempio n. 16
0
    void heartbeat(ThriftHeartbeatResponse& _return, const ThriftHeartbeatMessage& msg)
    {
        ::sailor::MutexLocker locker(&_mutex);
        // save msg
        HeartbeatMessage matrix_msg = to_matrix(msg);
        std::string out;
        Json::Value v = matrix_msg.to_json();
        Json::StyledWriter writer;
        out = writer.write(v);
        cout << "============================================================";
        cout << out << endl;
        cout << "============================================================";

        // set response
        _return = g_res;

        if(g_hb_count > 0) {
            g_hb_count --;
        }

        if(g_hb_count == 0) {
            LOG.info("HB count reach, quit");
            exit(0);
            return;
        }
    }
Esempio n. 17
0
bool JSONExporter::runOnScop(Scop &S) {
  std::string FileName = ImportDir + "/" + getFileName(S);

  Json::Value jscop = getJSON(S);
  Json::StyledWriter writer;
  std::string fileContent = writer.write(jscop);

  // Write to file.
  std::error_code EC;
  tool_output_file F(FileName, EC, llvm::sys::fs::F_Text);

  std::string FunctionName = S.getFunction().getName();
  errs() << "Writing JScop '" << S.getNameStr() << "' in function '"
         << FunctionName << "' to '" << FileName << "'.\n";

  if (!EC) {
    F.os() << fileContent;
    F.os().close();
    if (!F.os().has_error()) {
      errs() << "\n";
      F.keep();
      return false;
    }
  }

  errs() << "  error opening file for writing!\n";
  F.os().clear_error();

  return false;
}
/*
 * Create JSON data to store
 */
std::vector<uint8_t> Engine::SetupSnapshotData() {
  Json::StyledWriter writer;
  Json::Value root;

  root[JSON_KEY_VERSION] = JSON_VERSION;
  std::string strKey = std::string(JSON_KEY_LEVELS);
  for (int32_t i = 0; i < NUM_GAME_WORLD; ++i)
    for (int32_t j = 0; j < NUM_GAME_STAGES; ++j) {
      if (scores_[i][j]) {
        std::ostringstream str;
        str << i + 1 << "-" << j + 1;
        root[strKey][str.str()] = scores_[i][j];
      }
    }

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

  std::vector<uint8_t> v;
  auto it = source.begin();
  auto end = source.end();
  while (it != end) {
    uint8_t i = *it++;
    v.push_back(i);
  }

  LOGI("Created Game Data: size: %d", v.size());
  return v;
}
// These methods are the true native code we intend to reach from WebWorks
std::string DeviceEmailsNDK::getDefaultEmailAddress() {
	m_pParent->getLog()->debug("DeviceEmailsNDK.getDefaultEmailAddress");

	Json::StyledWriter writer;
	Json::Reader reader;
	Json::Value root;

	Account dAccount = m_accountService->defaultAccount(Service::Messages);
	QString emailAddress = dAccount.settingsProperty("email_address").value<QString>();
	std::string sEmail = emailAddress.toStdString();

	std::size_t found = sEmail.find('@');


	if(sEmail.length()>0 && found!=std::string::npos){
		root["success"]= true;
		root["defaultemail"]=sEmail;
		root["isEnterprise"]=(dAccount.isEnterprise())?true:false;
	}
	else{
		root["success"]= false;
	}
    std::string myJson = writer.write( root );
    return myJson;

}
Esempio n. 20
0
bool JSONExporter::runOnScop(Scop &scop) {
  S = &scop;
  Region &R = S->getRegion();

  std::string FileName = ImportDir + "/" + getFileName(S);

  Json::Value jscop = getJSON(scop);
  Json::StyledWriter writer;
  std::string fileContent = writer.write(jscop);

  // Write to file.
  std::string ErrInfo;
  tool_output_file F(FileName.c_str(), ErrInfo);

  std::string FunctionName = R.getEntry()->getParent()->getName();
  errs() << "Writing JScop '" << R.getNameStr() << "' in function '"
         << FunctionName << "' to '" << FileName << "'.\n";

  if (ErrInfo.empty()) {
    F.os() << fileContent;
    F.os().close();
    if (!F.os().has_error()) {
      errs() << "\n";
      F.keep();
      return false;
    }
  }

  errs() << "  error opening file for writing!\n";
  F.os().clear_error();

  return false;
}
Esempio n. 21
0
bool cPlayer::SaveToDisk()
{
    cFile::CreateFolder(FILE_IO_PREFIX + AString("players"));

    // create the JSON data
    Json::Value JSON_PlayerPosition;
    JSON_PlayerPosition.append(Json::Value(GetPosX()));
    JSON_PlayerPosition.append(Json::Value(GetPosY()));
    JSON_PlayerPosition.append(Json::Value(GetPosZ()));

    Json::Value JSON_PlayerRotation;
    JSON_PlayerRotation.append(Json::Value(GetRotation()));
    JSON_PlayerRotation.append(Json::Value(GetPitch()));
    JSON_PlayerRotation.append(Json::Value(GetRoll()));

    Json::Value JSON_Inventory;
    m_Inventory.SaveToJson(JSON_Inventory);

    Json::Value root;
    root["position"]       = JSON_PlayerPosition;
    root["rotation"]       = JSON_PlayerRotation;
    root["inventory"]      = JSON_Inventory;
    root["health"]         = m_Health;
    root["xpTotal"]        = m_LifetimeTotalXp;
    root["xpCurrent"]      = m_CurrentXp;
    root["air"]            = m_AirLevel;
    root["food"]           = m_FoodLevel;
    root["foodSaturation"] = m_FoodSaturationLevel;
    root["foodTickTimer"]  = m_FoodTickTimer;
    root["foodExhaustion"] = m_FoodExhaustionLevel;
    root["world"] = GetWorld()->GetName();

    if (m_GameMode == GetWorld()->GetGameMode())
    {
        root["gamemode"] = (int) eGameMode_NotSet;
    }
    else
    {
        root["gamemode"] = (int) m_GameMode;
    }

    Json::StyledWriter writer;
    std::string JsonData = writer.write(root);

    AString SourceFile;
    Printf(SourceFile, "players/%s.json", m_PlayerName.c_str() );

    cFile f;
    if (!f.Open(SourceFile, cFile::fmWrite))
    {
        LOGERROR("ERROR WRITING PLAYER \"%s\" TO FILE \"%s\" - cannot open file", m_PlayerName.c_str(), SourceFile.c_str());
        return false;
    }
    if (f.Write(JsonData.c_str(), JsonData.size()) != (int)JsonData.size())
    {
        LOGERROR("ERROR WRITING PLAYER JSON TO FILE \"%s\"", SourceFile.c_str());
        return false;
    }
    return true;
}
/**
 * Constructor 
 * @param equipletID identifier for the equiplet
 * @param moduleID identifier for the deltarobot
 **/
stewartGoughNodeNamespace::StewartGoughNode::StewartGoughNode(std::string equipletName, rexos_datatypes::ModuleIdentifier moduleIdentifier) :
		rexos_module::ActorModule::ActorModule(equipletName, moduleIdentifier),
		stewartGough(NULL),
		lastX(0.0),
		lastY(0.0),
		lastZ(0.0){
	REXOS_INFO("StewartGoughNode Constructor entering...");
	// get the properties and combine them for the deltarobot
	std::string properties = this->getModuleProperties();
	std::string typeProperties = this->getModuleTypeProperties();


	Json::Reader reader;
	Json::Value jsonNode;
	Json::Value typeJsonNode;
	reader.parse(properties, jsonNode);
	reader.parse(typeProperties, typeJsonNode);
	
	std::vector<std::string> typeJsonNodeMemberNames = typeJsonNode.getMemberNames();
	for(int i = 0; i < typeJsonNodeMemberNames.size(); i++) {
		jsonNode[typeJsonNodeMemberNames[i]] = typeJsonNode[typeJsonNodeMemberNames[i]];
	}

	Json::StyledWriter writer;
	ROS_INFO("%s", writer.write(jsonNode).c_str());
		
	// Create a stewart gough robot
	stewartGough = new rexos_stewart_gough::StewartGough(jsonNode);
}
Esempio n. 23
0
bool CConfig::save()
{
	std::wstring path = get_exe_path();
	path += L"\\";
	path += cfg;
	std::ofstream out(path); if (!out)return false;

	Json::Value value;
	std::string a;
	utf8::utf16to8(_cur_singer_id.begin(), _cur_singer_id.end(), std::back_inserter(a));
	value[keyCurSingerId] = a;

	value[keySerialKey] = _serial_key;
	if (!_singersCfg.empty()) {
		for (auto singer_cfg : _singersCfg) {
			//value[keySingers] = singer_cfg.first;
			//auto& singerValue = value[keySingers];
			for (auto song_cfg : singer_cfg.second) {
				value[keySingers][singer_cfg.first][song_cfg.first][keyListened] = song_cfg.second.first;
				value[keySingers][singer_cfg.first][song_cfg.first][keyTested] = song_cfg.second.second;
			}
		}
	}
	value[keyTotalScore] = _total_score;
#ifdef SAVE_UNZIP_PASSWD_2_CFG
	value[keyPasswd] = _unzip_passwd;
#endif


	Json::StyledWriter writer;
	out << writer.write(value);
	out.close();
	return true;
}
Esempio n. 24
0
int main(int argc, char* argv[]) {
  VertxBus vertxeb;
  vertxeb.Connect("https://localhost:8080/eventbus", 
  [&] {
    // OnOpen
    Json::Value jval;
    jval["name"] = "John";
    vertxeb.Send("test.hello", jval, VertxBus::ReplyHandler([&](const Json::Value& jmsg, const VertxBus::VertxBusReplier& vbr) {
      Json::StyledWriter writer;
      std::cout << "Received:\n" << writer.write(jmsg["body"]) << std::endl;
      vertxeb.Close();
    }));
  }, 
  [&](const std::error_code& ec) {
    // OnClose
    std::cout << "Connection closed." << std::endl;
  },
  [&](const std::error_code& ec, const Json::Value& jmsg_fail) {
    // OnFail
    std::cerr << "Connection failed: " << ec.message() << std::endl;

    if (!jmsg_fail.empty()) {
      Json::StyledWriter writer;
      std::cerr << writer.write(jmsg_fail) << std::endl;
    }
  });

  vertxeb.WaitClosed();

  return 0;
}
Esempio n. 25
0
int main(void)
{
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd == -1)
    {
        fprintf(stderr, "error: socket(client)!\n");
        exit(1);
    }

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("192.168.1.152");
    addr.sin_port = htons(8888);

    socklen_t sock_len = sizeof(struct sockaddr);

    //std::string send_buf;
    //char send_buf[128];
    //memset(send_buf, 0, sizeof(send_buf));
    Json::Value root;
    root["content"] = Json::Value("hello, world");
    Json::StyledWriter styledwriter;
    std::string send_buf = styledwriter.write(root);
    socklen_t len = sizeof(struct sockaddr);
    //int send_size = sendto(sockfd, send_buf.c_str(), send_buf.size(), 0, (struct sockaddr*)&addr, len);
    int send_size = sendto(sockfd, &send_buf, send_buf.size(), 0, (struct sockaddr*)&addr, len);
    std::cout<<"客户端已经发送的数据量为:"<<send_size<<std::endl;
    std::cout<<"所发送的内容为:"<<send_buf<<std::endl;

}
bool WriteDisplayData(Json::Value jDisplayList)
{
	Json::StyledWriter writer;
	std::string jsonString = writer.write(jDisplayList);
	
	if (!jsonString.length()) {
		return true;
	}

	char filePath[MAX_PATH];
	sprintf_s(filePath, "%s/DBM_MuseumData.json", GetUserDirectory().c_str());

	IFileStream	currentFile;
	IFileStream::MakeAllDirs(filePath);
	if (!currentFile.Create(filePath))
	{
		_ERROR("%s: couldn't create preset file (%s) Error (%d)", __FUNCTION__, filePath, GetLastError());
		return true;
	}

	currentFile.WriteBuf(jsonString.c_str(), jsonString.length());
	currentFile.Close();

	return false;
}
Esempio n. 27
0
extern "C" void network_error() {
  Json::Value writerRoot;
  writerRoot["result"] = 1;
  writerRoot["type"] = "network error";
  Json::StyledWriter writer;
  ThttpdInstance::getInstance()->PostMessage(writer.write(writerRoot));
}
Esempio n. 28
0
 void Config::writeLevelsGame() {
     char fileName [1024];
     sprintf (fileName, SETTINGS_JSON.c_str(), cocos2d::CCFileUtils::getWriteablePath().c_str());
     Json::Value root;
     unsigned long bufferSize = 0;
     unsigned char * uc =  cocos2d::CCFileUtils::getFileData(fileName,"a+", &bufferSize);
     if(bufferSize > 0) {
         char * ca = (char *) uc;
         string buffer = string(ca);
         Json::Reader reader;
         reader.parse(buffer.c_str(), root);
     }
     else {
         string fullPath = cocos2d::CCFileUtils::fullPathFromRelativePath(INITSETTINGS_JSON.c_str());
         
         unsigned long bufferSizeI = 0;
         unsigned char * dataI =  cocos2d::CCFileUtils::getFileData(fullPath.c_str(),"r", &bufferSizeI);
         char * ca = (char *) dataI;
         string buffer = string(ca);
         Json::Reader reader;
         reader.parse(buffer.c_str(), root);
         
         delete dataI;
     }
     delete uc;
     Json::StyledWriter writer;
     std::string outputString = writer.write(root);
     ofstream file;
     file.open(fileName);
     file << outputString;
     file.close();
 }
Esempio n. 29
0
std::string Socket::json_string()
{
	srand(time(NULL));
	int size ;
	while(1)
	{
		size = 50;//rand() % 100 ;
		if(size > 0)
		{
			break ;
		}
	}
	Json::Value root ;
	Json::Value arr ;
	while(size)
	{
		Json::Value elem ;
		char title[128] = "";
		char summary[128]="";
		sprintf(title , "tile_%d", size);
		sprintf(summary, "summary_%d", size);
		elem["title"] = title ;
		elem["summary"] = summary ;
		arr.append(elem);
		size -- ;
	}
	root["files"]=arr ;
	Json::FastWriter writer ;
	Json::StyledWriter stlwriter ;
	return stlwriter.write(root);

}
void ttt::JSONTissueTrackingProject::StoreProjectInfo(){

	Json::Value root;
	Json::StyledWriter writer;

	root["name"]=m_ProjectName;
	root["spacing"]["x"]=m_Spacing[0];
	root["spacing"]["y"]=m_Spacing[1];
	root["spacing"]["z"]=m_Spacing[2];
	root["samplingPeriod"]=m_SamplingPeriod;

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


	std::stringstream fileNameStream;
	fileNameStream << m_ProjectPath << "/" << "project.json";
	std::string projectConfigFile;
	fileNameStream >> projectConfigFile;

	std::ofstream file (projectConfigFile.c_str(), std::ofstream::out | std::ofstream::trunc);

	file << jsoncontent;

	file.close();

}