• json数据解析


    目录

    一、读数据

     1、简单对象读取

    2、数组读取

    3、对象读取

    二、写数据

    1、简单生成JSON

    2、对象数组JSON

    3、嵌套对象

    三、一个综合例子

    1、读JSON

    2、写JSON


    一、读数据

     1、简单对象读取

    1. {
    2. "app": "xnwVideo",
    3. "src": "C:\\build-video\\Output",
    4. "dest": "C:\\build-video\\1.0.32",
    5. "version": "1.0.32",
    6. "build": 32,
    7. "note": "布局json读取",
    8. "act": "All"
    9. }

    1. CBinBuf buf;
    2. buf.ReadFile("jsonInfo.json");
    3. CJsonObj json(buf);
    4. CBinBuf app, src, des, note, build, fullVersion, act;
    5. json.getString("app", app);
    6. json.getString("src", src);
    7. json.getString("dest", des);
    8. json.getString("note", note);
    9. json.getString("build", build);
    10. json.getString("version", fullVersion);
    11. json.getString("act", act);

    2、数组读取

    文件如下:

    1. [
    2. {
    3. "id": "Integrated Webcam:\\\\?\\usb#22vid_0c45&pid_671f&mi_00#226&8c5ffc6&0&0000#22{65e8773d-8f56-11d0-a3b9-00a0c9223196}\\global",
    4. "res": "1280x720"
    5. },
    6. {
    7. "id": "XSplit VCam:\\\\?\\root#22image#220000#22{65e8773d-8f56-11d0-a3b9-00a0c9223196}\\global",
    8. "res": "1280x720"
    9. },
    10. {
    11. "id": "YY开播:",
    12. "res": "1280x720"
    13. },
    14. {
    15. "id": "c922 Pro Stream Webcam:\\\\?\\usb#22vid_046d&pid_085c&mi_00#227&1e59b99a&0&0000#22{65e8773d-8f56-11d0-a3b9-00a0c9223196}\\global",
    16. "res": "1920x1080"
    17. }
    18. ]

    读取方式:

    1. std::map camIDResMap_;
    2. CBinBuf buf;
    3. buf.ReadFile(jsonPath.c_str());
    4. CJsonObj json(buf);
    5. for (int i = 0; i < json.get_arry_size(); ++i)
    6. {
    7. CJsonObj * pJson = json.get_arry_at(i);
    8. string id, res;
    9. pJson->getString("id", id);
    10. pJson->getString("res", res);
    11. camIDResMap_[id] = res;
    12. }

    类似的还有:

    1. for (int i = 0; i < class_info->get_arry_size(); ++i) {
    2. CJsonObj* pJson = class_info->get_arry_at(i);
    3. std::string courseID, chapterID, qID, chapterName, startTime, endTime, className, imgUrl;
    4. int nStatus;
    5. pJson->getString("course.id", courseID);
    6. pJson->getString("id", chapterID);
    7. pJson->getString("class.qid", qID);
    8. pJson->getString("name", chapterName);
    9. pJson->getString("start_time", startTime);
    10. pJson->getString("end_time", endTime);
    11. nStatus = pJson->getInt("live_status");
    12. /*
    13. CJsonObj* pCourseJson = pJson->getObj("course", err);
    14. pCourseJson->getString("name", className);
    15. pCourseJson->getString("cover_url", imgUrl);
    16. */
    17. pJson->getString("course.name", className);
    18. pJson->getString("course.cover_url", imgUrl);
    19. //time
    20. long iStartTime = atoi(startTime.c_str());
    21. long iEndTime = atoi(endTime.c_str());
    22. std::string timeStr = GetTimeStr(iStartTime, iEndTime);
    23. //添加列表中
    24. ui::ListContainerElement* pItem = dynamic_cast(ui::GlobalManager::CreateBoxWithCache(L"myClass/myclass_list_item.xml"));
    25. myClass_list->Add(pItem);
    26. if (curCourseId==courseID&&curChapterId==chapterID)
    27. {
    28. m_pCurItem = pItem; //刷新后,重置当前节点
    29. bCurItemReseted = TRUE;
    30. }
    31. //详细信息设置
    32. SetText(pItem, L"courseName", nbase::UTF8ToUTF16(className).c_str());
    33. SetText(pItem, L"chapterName", nbase::UTF8ToUTF16(chapterName).c_str());
    34. SetText(pItem, L"time", MyString::stows(timeStr).c_str());//asic->utf
    35. SetDataID(pItem, L"time", startTime);
    36. SetDataID(pItem, L"courseName", endTime); //此项利用上,保存这节课结束时间
    37. std::wstring statusStr;
    38. switch (nStatus)
    39. {
    40. case 0:
    41. statusStr = L"未开始";
    42. break;
    43. case 1:
    44. statusStr = L"正在直播";
    45. break;
    46. case 4:
    47. statusStr = L"正在直播";
    48. break;
    49. case 2:
    50. statusStr = L"已结束";
    51. break;
    52. case 3:
    53. statusStr = L"缺课";
    54. break;
    55. }
    56. SetText(pItem, L"live_status", statusStr);
    57. ui::Control* pClassPhoto = (ui::Control*)pItem->FindSubControl(L"classPhoto");
    58. if (pClassPhoto)
    59. {
    60. //根据Json 传来的照片网址,与本地地址映射
    61. //之所以加?做分隔符,是因为文件名不能包含?
    62. std::wstring url = nbase::UTF8ToUTF16(imgUrl);
    63. //此段代码用于线程下载时使用
    64. std::wstring IndexStr = std::to_wstring(i);
    65. std::wstring pathTemp = MyString::format(L"tmp\\classPhoto%s.png", IndexStr.c_str());
    66. std::wstring localPath = IndexStr + L"?" + localFoldPathW + pathTemp;
    67. std::wstring remotePath = IndexStr + L"|" + url;
    68. AddMapItem(remotePath, localPath);
    69. ///
    70. xnw_http_download(imgUrl.c_str(), GetHWND(), i);
    71. }
    72. ui::Button* pEnterLSRoomBtn = (ui::Button*)pItem->FindSubControl(L"enterLiveRoom_Btn");
    73. pEnterLSRoomBtn->AttachClick(nbase::Bind(&MyClassForm::EnterRoom, this, std::placeholders::_1));
    74. pItem->SetUTF8DataID(courseID); //设置item标识为章节ID
    75. pEnterLSRoomBtn->SetUTF8DataID(chapterID);
    76. pClassPhoto->SetUTF8DataID(qID);
    77. }
    78. if (!bCurItemReseted)
    79. {
    80. m_pCurItem = NULL;
    81. }
    82. }

    3、对象读取

    1. {
    2. "list": [
    3. {
    4. "name": "亮度92",
    5. "props": {
    6. "BacklightCompensation": 1,
    7. "Brightness": 92,
    8. "ColorEnable": 16,
    9. "Contrast": 91,
    10. "Gain": 16,
    11. "Gamma": 62,
    12. "Hue": 91,
    13. "Saturation": 255,
    14. "Sharpness": 62,
    15. "WhiteBalance": -1
    16. },
    17. "control": {
    18. "Exposure": -4,
    19. "Focus": 0,
    20. "Iris": 100,
    21. "Pan": 0,
    22. "Roll": 0,
    23. "Tilt": 0,
    24. "Zoom": 100
    25. }
    26. },
    27. {
    28. "name": "高亮170",
    29. "props": {
    30. "BacklightCompensation": 0,
    31. "Brightness": 170,
    32. "ColorEnable": 3,
    33. "Contrast": 128,
    34. "Gain": 3,
    35. "Gamma": 188,
    36. "Hue": 128,
    37. "Saturation": 128,
    38. "Sharpness": 188,
    39. "WhiteBalance": -1
    40. },
    41. "control": {
    42. "Exposure": -4,
    43. "Focus": 0,
    44. "Iris": 100,
    45. "Pan": 0,
    46. "Roll": 0,
    47. "Tilt": 0,
    48. "Zoom": 100
    49. }
    50. }
    51. ]
    52. }

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

    1. CJsonObj ampJson(jsonS.c_str());
    2. {
    3. int nCount = 0;
    4. int err;
    5. CJsonObj* arry = ampJson.getObj("list", err);
    6. if (arry && arry->isarray()) {
    7. nCount = arry->get_arry_size();
    8. std::string s;
    9. std::wstring name;
    10. for (int i = 0; i < arry->get_arry_size(); ++i) {
    11. CJsonObj* pJson = arry->get_arry_at(i);
    12. pJson->getString("name", s);
    13. name = to_wchar_t(s);
    14. g_SelfCamAmpPropNameVec.push_back(name);
    15. }
    16. }
    17. }

    类似的还有

    1. CBinBuf bfJson;
    2. if(bfJson.ReadFile(m_file)) {
    3. load(bfJson, 0);
    1. void load(const char* jstr, int merge) {
    2. uint32_t now = (uint32_t)time(0);
    3. CJsonObj js(jstr);
    4. m_tm = js.getInt("tm", 0);
    5. m_tmReport = js.getInt("tmReport", now);
    6. int err;
    7. CJsonObj* pList = js.getObj("list", err);
    8. if(pList) {
    9. std::vector v, vOld;
    10. if(merge) {
    11. for(int i=0; isize(); ++i) vOld.push_back(m_vCdn[i]);
    12. }
    13. m_vCdn.clear();
    14. for(int i=0; iget_arry_size(); ++i) {
    15. CDNINFO c;
    16. CJsonObj* pItem = pList->get_arry_at(i);
    17. c.from(pItem);
    18. add(c, merge, vOld);
    19. }
    20. }
    21. }


     

    二、写数据

    1、简单生成JSON

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

      又如,

    1. void MakeDefaultJson(CJsonString &jsonStr){
    2. jsonStr.append_item("is_beauty_on", 1); //美颜全局开关,0为关,1为开,默认为1
    3. //滤镜
    4. jsonStr.append_item("filter_level", 0); //0-10 ->[0,1] 取值范围 0.0-1.0,0.0为无效果,1.0为最大效果,默认值1.0
    5. jsonStr.append_item("filter_name", "origin");
    6. //美白
    7. jsonStr.append_item("color_level", 2); //0-20 [0,2.0] 取值范围 0.0-2.0,0.0为无效果,2.0为最大效果,默认值0.2
    8. //红润
    9. jsonStr.append_item("red_level", 5); //0-20 [0,2.0] 取值范围 0.0-2.0,0.0为无效果,2.0为最大效果,默认值0.5
    10. //磨皮程度
    11. jsonStr.append_item("blur_level", 60); //[0,6.0] 磨皮程度,取值范围0.0-6.0,默认6.0
    12. jsonStr.append_item("skin_detect", 0); //肤色检测开关,0为关,1为开 默认0
    13. jsonStr.append_item("nonskin_blur_scale", 0); //0-10 [0,1]肤色检测之后非肤色区域的融合程度,取值范围0.0-1.0,默认0.0
    14. jsonStr.append_item("heavy_blur", 0); //朦胧磨皮开关,0为清晰磨皮,1为朦胧磨皮
    15. jsonStr.append_item("blur_type", 2); //此参数优先级比heavy_blur低,在使用时要将heavy_blur设为0,0 清晰磨皮 1 朦胧磨皮 2精细磨皮
    16. jsonStr.append_item("blur_use_mask", 0); //ios端默认为1,其他端默认为0。1为开启基于人脸的磨皮mask,0为不使用mask正常磨皮。只在blur_type为2时生效。
    17. jsonStr.append_item("sharpen", 2); //锐化程度,取值范围0.0-1.0,默认0.2
    18. jsonStr.close();
    19. //jsonStr.WriteFile("jsonInfoRes.json");
    20. }

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

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

    2、对象数组JSON

    1. CJsonString jsonStr;
    2. jsonStr.begin("[");
    3. for (auto &it : camIDResMap)
    4. {
    5. CJsonString camJson;
    6. camJson.begin("{");
    7. camJson.append_item("id", it.first.c_str());
    8. camJson.append_item("res", it.second.c_str());
    9. camJson.close("}");
    10. jsonStr.append_obj(camJson);
    11. }
    12. jsonStr.close("]");
    13. jsonStr.WriteFile(m_camjsonPath);

    3、嵌套对象

    1. {
    2. "list": [
    3. {
    4. "name": "亮度92",
    5. "props": {
    6. "BacklightCompensation": 1,
    7. "Brightness": 92
    8. },
    9. "control": {
    10. "Exposure": -4,
    11. "Zoom": 100
    12. }
    13. },
    14. {
    15. "name": "高亮170",
    16. "props": {
    17. "BacklightCompensation": 0,
    18. "WhiteBalance": -1
    19. },
    20. "control": {
    21. "Exposure": -4,
    22. "Zoom": 100
    23. }
    24. }
    25. ]
    26. }

    1. CJsonString jsonStr;
    2. jsonStr.begin("[");
    3. int nCount = 0;
    4. for (auto &it : selfCamPros_)
    5. {
    6. std::mapint> &Map = it.second;
    7. std::wstring nameW = it.first;
    8. std::mapint> &ctlMap = selfCamControls_[nameW];
    9. std::string name = to_string(nameW);
    10. CJsonString camAllJson;
    11. camAllJson.begin("{");
    12. camAllJson.append_item("name", name.c_str());
    13. CJsonString ampJsonObj;
    14. ampJsonObj.begin("{");
    15. auto oneAmpIt = ampMap.begin();
    16. while (oneAmpIt != ampMap.end())
    17. {
    18. ampJsonObj.append_item(oneAmpIt->first.c_str(), oneAmpIt->second);
    19. oneAmpIt++;
    20. }
    21. ampJsonObj.close("}");
    22. camAllJson.append_obj("props", ampJsonObj);
    23. CJsonString ctlJsonObj;
    24. ctlJsonObj.begin("{");
    25. auto oneCtlIt = ctlMap.begin();
    26. while (oneCtlIt != ctlMap.end())
    27. {
    28. ctlJsonObj.append_item(oneCtlIt->first.c_str(), oneCtlIt->second);
    29. oneCtlIt++;
    30. }
    31. ctlJsonObj.close("}");
    32. camAllJson.append_obj("control", ctlJsonObj);
    33. camAllJson.close("}");
    34. jsonStr.append_obj(camAllJson);
    35. }
    36. jsonStr.close("]");
    37. CJsonString listObjJsonS;
    38. listObjJsonS.begin("{");
    39. listObjJsonS.append_obj("list", jsonStr);
    40. listObjJsonS.close("}");
    41. listObjJsonS.WriteFile(sysJsonPath);

    又如,

    1. CJsonString js, list;
    2. js.append_item_u32("tm", m_tm);
    3. js.append_item_u32("tmReport", m_tmReport);
    4. format_json(list);
    5. js.append_obj("list", list);
    6. js.close("}");
    7. js.WriteFile(m_file);
    1. void format_json(CJsonString& js) {
    2. js.begin("[");
    3. size_t n = m_vCdn.size();
    4. for(int i=0; i
    5. CDNINFO& c = m_vCdn[i];
    6. CJsonString cdn;
    7. c.format(cdn);
    8. js.append_obj(cdn);
    9. }
    10. js.close("]");
    11. }

    又如,

    1. CJsonString js,list;
    2. list.begin("[");
    3. for (auto it = nameVec.begin(); it != nameVec.end(); it++)
    4. {
    5. CJsonString jsObj;
    6. std::wstring name = *it;
    7. if (name == L"类别")
    8. continue;
    9. std::string name8 = nbase::UTF16ToUTF8(name);
    10. jsObj.begin("{");
    11. jsObj.append_item("name", name8.c_str());
    12. jsObj.close("}");
    13. list.append_obj(jsObj);
    14. }
    15. list.close("]");
    16. js.append_obj("list", list);
    17. js.close("}");
    18. js.WriteFile("d:\\name.json");

    三、一个综合例子

    1、JSON路径

    1. std::string GetXnwAccountJsonPath(){
    2. static std::string path;
    3. if (!path.empty())
    4. {
    5. return path;
    6. }
    7. std::wstring pathaW;
    8. if (BCurDirHaveWriteAuthority())
    9. pathaW = appFolderW + L"\\account.json";
    10. else
    11. pathaW = GetXnwSysAppDataDirW() + L"\\account.json";
    12. path = nbase::UTF16ToUTF8(pathaW);
    13. return path;
    14. }

    2、读JSON

    1. std::set acountSet_;
    2. std::set acountPhoneSet_;
    3. void ReadAcountSet()
    4. {
    5. std::string path = GetXnwAccountJsonPath();
    6. CBinBuf buf;
    7. if (buf.Read(path.c_str()))
    8. {
    9. CJsonObj json(buf);
    10. int err;
    11. CJsonObj* arry = json.getObj("nameArr", err);
    12. if (arry && arry->isarray())
    13. {
    14. for (int i = 0; i < arry->get_arry_size(); ++i)
    15. {
    16. CJsonObj * pJson = arry->get_arry_at(i);
    17. std::string name;
    18. pJson->getString("account", name);
    19. if (!name.empty())
    20. {
    21. std::wstring namew = nbase::UTF8ToUTF16(name);
    22. acountSet_.insert(namew);
    23. }
    24. }
    25. }
    26. arry = json.getObj("phoneArr", err);
    27. if (arry && arry->isarray())
    28. {
    29. for (int i = 0; i < arry->get_arry_size(); ++i)
    30. {
    31. CJsonObj * pJson = arry->get_arry_at(i);
    32. std::string name;
    33. pJson->getString("account", name);
    34. std::wstring namew = nbase::UTF8ToUTF16(name);
    35. acountPhoneSet_.insert(namew);
    36. }
    37. }
    38. arry = json.getObj("apiArr", err);
    39. if (arry && arry->isarray())
    40. {
    41. for (int i = 0; i < arry->get_arry_size(); ++i)
    42. {
    43. CJsonObj* pJson = arry->get_arry_at(i);
    44. std::string account;
    45. std::string api;
    46. pJson->getString("account", account);
    47. pJson->getString("api", api);
    48. g_AccoutApiMap[account] = api;
    49. }
    50. }
    51. }
    52. }

    3、保存JSON

    1. void SaveAcountSet()
    2. {
    3. std::string path = GetXnwAccountJsonPath();
    4. CJsonString listJsonStr;
    5. listJsonStr.begin("{");
    6. CJsonString jsonStr;
    7. jsonStr.begin("[");
    8. for (auto &it : acountSet_)
    9. {
    10. std::string name = nbase::UTF16ToUTF8(it);
    11. CJsonString json;
    12. json.begin("{");
    13. json.append_item("account", name.c_str());
    14. json.close("}");
    15. jsonStr.append_obj(json);
    16. }
    17. jsonStr.close("]");
    18. listJsonStr.append_obj("nameArr", jsonStr);
    19. CJsonString jsonStr2;
    20. jsonStr2.begin("[");
    21. for (auto &it : acountPhoneSet_)
    22. {
    23. std::string name = nbase::UTF16ToUTF8(it);
    24. CJsonString json;
    25. json.begin("{");
    26. json.append_item("account", name.c_str());
    27. json.close("}");
    28. jsonStr2.append_obj(json);
    29. }
    30. jsonStr2.close("]");
    31. listJsonStr.append_obj("phoneArr", jsonStr2);
    32. CJsonString jsonStr3;
    33. jsonStr3.begin("[");
    34. for (auto& it : g_AccoutApiMap)
    35. {
    36. std::string account = it.first;
    37. std::string api = it.second;
    38. CJsonString json;
    39. json.begin("{");
    40. json.append_item("account", account.c_str());
    41. json.append_item("api", api.c_str());
    42. json.close("}");
    43. jsonStr3.append_obj(json);
    44. }
    45. jsonStr3.close("]");
    46. listJsonStr.append_obj("apiArr", jsonStr3);
    47. listJsonStr.close("}");
    48. listJsonStr.WriteFile(path.c_str());
    49. }

  • 相关阅读:
    力扣每日一题70:爬楼梯
    赶紧收藏!2024 年最常见 20道 Kafka面试题(三)
    【iOS开发- KVO(键值监听)】
    深度神经网络的应用,深度神经网络应用
    ffmpeg深度学习滤镜
    Baumer工业相机堡盟工业相机如何通过BGAPI SDK设置相机的图像剪切(ROI)功能(C#)
    【FaceRevelio】一种用于智能手机的带有前置摄像头的 人脸活跃度检测系统
    ITSM和ITIL有什么区别?
    ns3-gym入门(三):在opengym基础上实现一个小小的demo
    VRPTW(MATLAB):淘金优化算法GRO求解带时间窗的车辆路径问题VRPTW(提供参考文献及MATLAB代码)
  • 原文地址:https://blog.csdn.net/shuilan0066/article/details/98732237