博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

jsoncpp用法通俗易懂之将数据合成json格式

Posted on 2015-02-26 18:41  勇敢的鑫  阅读(585)  评论(0编辑  收藏  举报
void *upload(void *pParam)
{
	CUpSender *s = (CUpSender*)pParam;
	map<string, string> mx;
	char tmp[20] = {0};
	char filename[50] = {0};
	string data = "";
	while(1)
	{
		mx.clear();
		FileLog(FILENAME, "in thread m_urlcount = [%d]", s->m_urlcount);
		while(s->m_urlcount == 0)
		{
			FileLog(FILENAME, "there is no count files....wait ten seconds!!!!");
			sleep(10);
		}
		//这里是将id的那部分获取出来存入map中
		for(int i = 1; i != s->m_urlcount + 1; i++)
		{
			memset(tmp, 0, sizeof(tmp));
			memset(filename, 0, sizeof(filename));
			snprintf(tmp, sizeof(tmp), "%d", i);
			snprintf(filename, sizeof(filename), "/apps/hotel/run_env/bin/id/%d", i);
			ifstream iis(filename);
			getline(iis, mx[tmp]);
			FileLog(FILENAME, "read urlcount from %d = %s", filename, mx[tmp].c_str());
		}
		//这里开始组合
		Json::Value root;
		Json::Value roott;
     	Json::Value arrayObj;
     	Json::Value item;
		for(map<string, string>::iterator it = mx.begin(); it != mx.end(); it++)
		{
			item["id"] = it->first;
			arrayObj.append(item);
		}
		roott["mac"] = s->m_strDevMac;
		roott["uploadfrequency"] = s->m_uploadfrequency;
		roott["urls"] = arrayObj;
		root["uwdupload"] = roott;
		data = root.toStyledString();
		FileLog(FILENAME, "the thread will send to peng webservice data : [%s], url = [%s]", data.c_str(), (s->m_threadurl).c_str());
		s->SendCmd1(data, s->m_threadurl);
		FileLog(FILENAME, "the thread sleeptime is : [%d]", s->m_threadtime);
		sleep(s->m_threadtime);
	}
}

  上边是合成的过程。

{
	"uwdupload":{
    	"mac": "F0:D1:A9:C9:56:E8",
 		"uploadfrequency": "180",
 	"urls": [
            {
	    "id": "1",
               "total": "100",
            },
            {
 	    "id": "2",
               "total": "50",
            },
            {
                "id": "3",
                "total": "20",
            }
         ]
   }
}

  这是合成的结果。思想类同解析。