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);//timelong 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->utfSetDataID(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标识为章节IDpEnterLSRoomBtn->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.0jsonStr.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.0jsonStr.append_item("skin_detect", 0); //肤色检测开关,0为关,1为开 默认0jsonStr.append_item("nonskin_blur_scale", 0); //0-10 [0,1]肤色检测之后非肤色区域的融合程度,取值范围0.0-1.0,默认0.0jsonStr.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.2jsonStr.close();//jsonStr.WriteFile("jsonInfoRes.json");
}
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> &Map = 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");
三、一个综合例子
{"nameArr": [{"account": "张三"},{"account": "王五"},{"account": "李四"}],"phoneArr": [{"account": "1800000"}]
}
1、读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);}}}}
2、写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);listJsonStr.close("}");listJsonStr.WriteFile(path.c_str());
}