json数据解析

目录

一、读数据

 1、简单对象读取

2、数组读取

3、对象读取

二、写数据

1、简单生成JSON

2、对象数组JSON

3、嵌套对象

三、一个综合例子

1、读JSON

2、写JSON


一、读数据

 1、简单对象读取

{
  "app": "xnwVideo",
  "src": "C:\\build-video\\Output",
  "dest": "C:\\build-video\\1.0.32",
  "version": "1.0.32",
  "build": 32,
  "note": "布局json读取",
  "act": "All"
}

		CBinBuf buf;
		buf.ReadFile("jsonInfo.json");
		CJsonObj json(buf);

		CBinBuf app, src, des, note, build, fullVersion, act;
		json.getString("app", app);
		json.getString("src", src);
		json.getString("dest", des);
		json.getString("note", note);
		json.getString("build", build);
		json.getString("version", fullVersion);
		json.getString("act", act);

2、数组读取

文件如下:

[
  {
    "id": "Integrated Webcam:\\\\?\\usb#22vid_0c45&pid_671f&mi_00#226&8c5ffc6&0&0000#22{65e8773d-8f56-11d0-a3b9-00a0c9223196}\\global",
    "res": "1280x720"
  },
  {
    "id": "XSplit VCam:\\\\?\\root#22image#220000#22{65e8773d-8f56-11d0-a3b9-00a0c9223196}\\global",
    "res": "1280x720"
  },
  {
    "id": "YY开播:",
    "res": "1280x720"
  },
  {
    "id": "c922 Pro Stream Webcam:\\\\?\\usb#22vid_046d&pid_085c&mi_00#227&1e59b99a&0&0000#22{65e8773d-8f56-11d0-a3b9-00a0c9223196}\\global",
    "res": "1920x1080"
  }
]

读取方式:

	std::map<std::string, std::string > camIDResMap_;


	CBinBuf buf;
	buf.ReadFile(jsonPath.c_str());
	CJsonObj json(buf);

	for (int i = 0; i < json.get_arry_size(); ++i)
	{
		CJsonObj * pJson = json.get_arry_at(i);
		string id, res;
		pJson->getString("id", id);
		pJson->getString("res", res);

		camIDResMap_[id] = res;
	}

类似的还有:

			for (int i = 0; i < class_info->get_arry_size(); ++i) {
				CJsonObj* pJson = class_info->get_arry_at(i);

				std::string courseID, chapterID, qID, chapterName, startTime, endTime, className, imgUrl;
				int nStatus;

				pJson->getString("course.id", courseID);
				pJson->getString("id", chapterID);				
				pJson->getString("class.qid", qID);


				pJson->getString("name", chapterName);
				
				pJson->getString("start_time", startTime);
				pJson->getString("end_time", endTime);
				nStatus = pJson->getInt("live_status");

				/*
								CJsonObj* pCourseJson = pJson->getObj("course", err);
								pCourseJson->getString("name", className);								
								pCourseJson->getString("cover_url", imgUrl);
				*/
				
				pJson->getString("course.name", className);
				pJson->getString("course.cover_url", imgUrl);
				


				//time
				long iStartTime = atoi(startTime.c_str());
				long iEndTime = atoi(endTime.c_str());
				std::string timeStr = GetTimeStr(iStartTime, iEndTime);

				//添加列表中
				ui::ListContainerElement* pItem = dynamic_cast<ui::ListContainerElement*>(ui::GlobalManager::CreateBoxWithCache(L"myClass/myclass_list_item.xml"));
				myClass_list->Add(pItem);


				if (curCourseId==courseID&&curChapterId==chapterID)
				{
					m_pCurItem = pItem; //刷新后,重置当前节点

					bCurItemReseted = TRUE;
				}


			
				//详细信息设置
				SetText(pItem, L"courseName", nbase::UTF8ToUTF16(className).c_str());
				SetText(pItem, L"chapterName", nbase::UTF8ToUTF16(chapterName).c_str());
				SetText(pItem, L"time", MyString::stows(timeStr).c_str());//asic->utf
				SetDataID(pItem, L"time", startTime);
				SetDataID(pItem, L"courseName", endTime);    //此项利用上,保存这节课结束时间


				std::wstring statusStr;
				switch (nStatus)
				{
				case 0:
					statusStr = L"未开始";
					break;

				case 1:
					statusStr = L"正在直播";
					break;
				case 4:
					statusStr = L"正在直播";
					break;

				case 2:
					statusStr = L"已结束";
					break;

				case 3:
					statusStr = L"缺课";
					break;
				}
				SetText(pItem, L"live_status", statusStr);


				ui::Control* pClassPhoto = (ui::Control*)pItem->FindSubControl(L"classPhoto");
				if (pClassPhoto)
				{
					//根据Json  传来的照片网址,与本地地址映射
					//之所以加?做分隔符,是因为文件名不能包含?

					std::wstring url = nbase::UTF8ToUTF16(imgUrl);

					//此段代码用于线程下载时使用
					std::wstring IndexStr = std::to_wstring(i);
					std::wstring pathTemp = MyString::format(L"tmp\\classPhoto%s.png", IndexStr.c_str());
					std::wstring localPath = IndexStr + L"?" + localFoldPathW + pathTemp;
					std::wstring remotePath = IndexStr + L"|" + url;
					AddMapItem(remotePath, localPath);
					///

					xnw_http_download(imgUrl.c_str(), GetHWND(), i);
				}

				ui::Button* pEnterLSRoomBtn = (ui::Button*)pItem->FindSubControl(L"enterLiveRoom_Btn");				
				pEnterLSRoomBtn->AttachClick(nbase::Bind(&MyClassForm::EnterRoom, this, std::placeholders::_1));
			
				pItem->SetUTF8DataID(courseID); //设置item标识为章节ID
				pEnterLSRoomBtn->SetUTF8DataID(chapterID);
				pClassPhoto->SetUTF8DataID(qID);
			}

			if (!bCurItemReseted)
			{
				m_pCurItem = NULL;
			}
		}

3、对象读取

{
  "list": [
    {
      "name": "亮度92",
      "props": {
        "BacklightCompensation": 1,
        "Brightness": 92,
        "ColorEnable": 16,
        "Contrast": 91,
        "Gain": 16,
        "Gamma": 62,
        "Hue": 91,
        "Saturation": 255,
        "Sharpness": 62,
        "WhiteBalance": -1
      },
      "control": {
        "Exposure": -4,
        "Focus": 0,
        "Iris": 100,
        "Pan": 0,
        "Roll": 0,
        "Tilt": 0,
        "Zoom": 100
      }
    },
    {
      "name": "高亮170",
      "props": {
        "BacklightCompensation": 0,
        "Brightness": 170,
        "ColorEnable": 3,
        "Contrast": 128,
        "Gain": 3,
        "Gamma": 188,
        "Hue": 128,
        "Saturation": 128,
        "Sharpness": 188,
        "WhiteBalance": -1
      },
      "control": {
        "Exposure": -4,
        "Focus": 0,
        "Iris": 100,
        "Pan": 0,
        "Roll": 0,
        "Tilt": 0,
        "Zoom": 100
      }
    }
  ]
}

对象的值又是数组的情况下,读取方式


	CJsonObj ampJson(jsonS.c_str());

	{
		int nCount = 0;
		int err;

		CJsonObj* arry = ampJson.getObj("list", err);
		if (arry && arry->isarray()) {
			nCount = arry->get_arry_size();
			std::string s;
			std::wstring name;

			for (int i = 0; i < arry->get_arry_size(); ++i) {

				CJsonObj* pJson = arry->get_arry_at(i);
				pJson->getString("name", s);
				name = to_wchar_t(s);

				g_SelfCamAmpPropNameVec.push_back(name);
			}

		}
	}

类似的还有

    CBinBuf bfJson;
    if(bfJson.ReadFile(m_file)) {
        load(bfJson, 0);
    void load(const char* jstr, int merge) {
        uint32_t now = (uint32_t)time(0);
        CJsonObj js(jstr);
        m_tm = js.getInt("tm", 0);
        m_tmReport = js.getInt("tmReport", now);
        int err;
        CJsonObj* pList = js.getObj("list", err);
        if(pList) {
            std::vector<CDNINFO> v, vOld;
            if(merge) {
                for(int i=0; i<m_vCdn.size(); ++i) vOld.push_back(m_vCdn[i]);
            }
            m_vCdn.clear();
            for(int i=0; i<pList->get_arry_size(); ++i) {
                CDNINFO c;
                CJsonObj* pItem = pList->get_arry_at(i);
                c.from(pItem);
                add(c, merge, vOld);
            }
        }
    }


 

二、写数据

1、简单生成JSON

	CJsonString bf("{");
	bf.append_item("file", szUtf8);
	bf.append_item("url", cbitem->url);
	bf.append_item("wparam",(uint64_t)cbitem->wParam);
	bf.close("}");

  又如,

void MakeDefaultJson(CJsonString &jsonStr){

	jsonStr.append_item("is_beauty_on", 1); //美颜全局开关,0为关,1为开,默认为1

	//滤镜 
	jsonStr.append_item("filter_level", 0);   //0-10  ->[0,1] 取值范围 0.0-1.0,0.0为无效果,1.0为最大效果,默认值1.0
	jsonStr.append_item("filter_name", "origin");

	//美白
	jsonStr.append_item("color_level", 2);    //0-20  [0,2.0] 取值范围 0.0-2.0,0.0为无效果,2.0为最大效果,默认值0.2
	//红润
	jsonStr.append_item("red_level", 5);      //0-20  [0,2.0] 取值范围 0.0-2.0,0.0为无效果,2.0为最大效果,默认值0.5

	//磨皮程度
	jsonStr.append_item("blur_level", 60);        //[0,6.0] 磨皮程度,取值范围0.0-6.0,默认6.0
	jsonStr.append_item("skin_detect", 0);        //肤色检测开关,0为关,1为开 默认0
	jsonStr.append_item("nonskin_blur_scale", 0); //0-10 [0,1]肤色检测之后非肤色区域的融合程度,取值范围0.0-1.0,默认0.0

	jsonStr.append_item("heavy_blur", 0);         //朦胧磨皮开关,0为清晰磨皮,1为朦胧磨皮
	jsonStr.append_item("blur_type", 2);          //此参数优先级比heavy_blur低,在使用时要将heavy_blur设为0,0 清晰磨皮  1 朦胧磨皮  2精细磨皮
	jsonStr.append_item("blur_use_mask", 0);      //ios端默认为1,其他端默认为0。1为开启基于人脸的磨皮mask,0为不使用mask正常磨皮。只在blur_type为2时生效。

	jsonStr.append_item("sharpen", 2);            //锐化程度,取值范围0.0-1.0,默认0.2

	jsonStr.close();
	//jsonStr.WriteFile("jsonInfoRes.json");
}

参考: c++  一个经典的json库 生成json串方法

 
	Json::Value value;
	value["x"] = 1;
	value["y"] = 2;
	value["w"] = 3;
 
	std::string  styleS = value.toStyledString();

2、对象数组JSON

	CJsonString jsonStr;
	jsonStr.begin("[");

	for (auto &it : camIDResMap)
	{
		CJsonString camJson;
		camJson.begin("{");
		camJson.append_item("id", it.first.c_str());
		camJson.append_item("res", it.second.c_str());

		camJson.close("}");
		jsonStr.append_obj(camJson);
	}

	jsonStr.close("]");

	jsonStr.WriteFile(m_camjsonPath);

3、嵌套对象

{
  "list": [
    {
      "name": "亮度92",
      "props": {
        "BacklightCompensation": 1,
        "Brightness": 92
      },
      "control": {
        "Exposure": -4,
        "Zoom": 100
      }
    },
    {
      "name": "高亮170",
      "props": {
        "BacklightCompensation": 0,
        "WhiteBalance": -1
      },
      "control": {
        "Exposure": -4,
        "Zoom": 100
      }
    }
  ]
}


	CJsonString jsonStr;
	jsonStr.begin("[");

	int nCount = 0;

	for (auto &it : selfCamPros_)
	{
		std::map<std::string, int> &ampMap = it.second;
		std::wstring nameW = it.first;

		std::map<std::string, int> &ctlMap = selfCamControls_[nameW];

		std::string name = to_string(nameW);

		CJsonString camAllJson;
		camAllJson.begin("{");
		camAllJson.append_item("name", name.c_str());

		CJsonString ampJsonObj;
		ampJsonObj.begin("{");
		auto oneAmpIt = ampMap.begin();
		while (oneAmpIt != ampMap.end())
		{
			ampJsonObj.append_item(oneAmpIt->first.c_str(), oneAmpIt->second);
			oneAmpIt++;
		}

		ampJsonObj.close("}");
		camAllJson.append_obj("props", ampJsonObj);


		CJsonString ctlJsonObj;
		ctlJsonObj.begin("{");
		auto oneCtlIt = ctlMap.begin();
		while (oneCtlIt != ctlMap.end())
		{
			ctlJsonObj.append_item(oneCtlIt->first.c_str(), oneCtlIt->second);
			oneCtlIt++;
		}
		ctlJsonObj.close("}");
		camAllJson.append_obj("control", ctlJsonObj);



		camAllJson.close("}");


		jsonStr.append_obj(camAllJson);
	}

	jsonStr.close("]");


	CJsonString listObjJsonS;
	listObjJsonS.begin("{");
	listObjJsonS.append_obj("list", jsonStr);
	listObjJsonS.close("}");


	listObjJsonS.WriteFile(sysJsonPath);

又如,

        CJsonString js, list;
        js.append_item_u32("tm", m_tm);
        js.append_item_u32("tmReport", m_tmReport);
        format_json(list);
        js.append_obj("list", list);
        js.close("}");
        js.WriteFile(m_file);
    void format_json(CJsonString& js) {
        js.begin("[");
        size_t n = m_vCdn.size();
        for(int i=0; i<n; ++i) {
            CDNINFO& c = m_vCdn[i];
            CJsonString cdn;
            c.format(cdn);
            js.append_obj(cdn);
        }
        js.close("]");
    }


又如,

		CJsonString js,list;
		list.begin("[");

		for (auto it = nameVec.begin(); it != nameVec.end(); it++)
		{

			CJsonString jsObj;
			std::wstring name = *it;

			if (name == L"类别")
				continue;

			std::string name8 = nbase::UTF16ToUTF8(name);

			jsObj.begin("{");
			jsObj.append_item("name", name8.c_str());
			jsObj.close("}");

			list.append_obj(jsObj);
		}
		list.close("]");

		js.append_obj("list", list);
		js.close("}");
		js.WriteFile("d:\\name.json");

三、一个综合例子

1、JSON路径

std::string GetXnwAccountJsonPath(){

	static std::string path;	
	if (!path.empty())
	{
		return path;
	}

	std::wstring pathaW;

	if (BCurDirHaveWriteAuthority())
		pathaW = appFolderW + L"\\account.json";
	else
		pathaW = GetXnwSysAppDataDirW() + L"\\account.json";

	path = nbase::UTF16ToUTF8(pathaW);
	return path;
}

2、读JSON

	std::set<std::wstring> acountSet_;

	std::set<std::wstring> acountPhoneSet_;

void ReadAcountSet()
{
	std::string path = GetXnwAccountJsonPath();

	CBinBuf buf;
	if (buf.Read(path.c_str()))
	{
		CJsonObj json(buf);
		int err;
		CJsonObj* arry = json.getObj("nameArr", err);
		if (arry && arry->isarray())
		{
		
			for (int i = 0; i < arry->get_arry_size(); ++i)
			{
				CJsonObj * pJson = arry->get_arry_at(i);
				std::string name;
				pJson->getString("account", name);

				if (!name.empty())
				{
					std::wstring namew = nbase::UTF8ToUTF16(name);
					acountSet_.insert(namew);
				}


			}

		}

		arry = json.getObj("phoneArr", err);
		if (arry && arry->isarray())
		{

			for (int i = 0; i < arry->get_arry_size(); ++i)
			{
				CJsonObj * pJson = arry->get_arry_at(i);
				std::string name;
				pJson->getString("account", name);

				std::wstring namew = nbase::UTF8ToUTF16(name);
				acountPhoneSet_.insert(namew);

			}

		}

         arry = json.getObj("apiArr", err);
		if (arry && arry->isarray())
		{

			for (int i = 0; i < arry->get_arry_size(); ++i)
			{
				CJsonObj* pJson = arry->get_arry_at(i);
				std::string account;
				std::string api;
				pJson->getString("account", account);
				pJson->getString("api", api);
				g_AccoutApiMap[account] = api;

			}
		}

	}



}

3、保存JSON

void SaveAcountSet()
{

	std::string path = GetXnwAccountJsonPath();

	CJsonString listJsonStr;
	listJsonStr.begin("{");

	CJsonString jsonStr;
	jsonStr.begin("[");


	for (auto &it : acountSet_)
	{
		std::string name = nbase::UTF16ToUTF8(it);
		CJsonString json;

		json.begin("{");
		json.append_item("account", name.c_str());
		json.close("}");

		jsonStr.append_obj(json);
	}

	jsonStr.close("]");

	listJsonStr.append_obj("nameArr", jsonStr);


	CJsonString jsonStr2;
	jsonStr2.begin("[");
	for (auto &it : acountPhoneSet_)
	{
		std::string name = nbase::UTF16ToUTF8(it);
		CJsonString json;

		json.begin("{");
		json.append_item("account", name.c_str());
		json.close("}");

		jsonStr2.append_obj(json);
	}

	jsonStr2.close("]");
	listJsonStr.append_obj("phoneArr", jsonStr2);


	CJsonString jsonStr3;
	jsonStr3.begin("[");
	for (auto& it : g_AccoutApiMap)
	{
		std::string account = it.first;
		std::string api = it.second;

		CJsonString json;

		json.begin("{");
		json.append_item("account", account.c_str());
		json.append_item("api", api.c_str());
		json.close("}");

		jsonStr3.append_obj(json);
	}

	jsonStr3.close("]");

	listJsonStr.append_obj("apiArr", jsonStr3);



	listJsonStr.close("}");

	listJsonStr.WriteFile(path.c_str());
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清水迎朝阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值